在C ++中对外部命令的线程安全并发调用 [英] Thread-Safe Concurrent call to external command in c++

查看:97
本文介绍了在C ++中对外部命令的线程安全并发调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在Internet上四处寻找,试图找到一种方法来从我的C ++程序中以线程安全的方式并发调用外部程序. 据我了解,popen,system和fork都不是线程安全的. 在我看来,这里缺少一些东西,到目前为止我还找不到.是否有可能无法从不同线程进行并发调用到外部程序?因为在我看来,这将是使用多线程编码的第一个示例. 我正在使用linux(mandriva),可以在不同的Shell中同时调用我想调用的外部程序. 我不是C ++的新手,而是多线程的新手,因此,我将非常感谢您提供有关此主题的任何建议. 马塞洛

I've been looking around on the internet trying to find a way to make concurrent calls to an external program in a thread safe manner from within my C++ program. As far as I've understood, popen, system and fork are not thread safe. It seems to me that there is something missing here, that I haven't been able to find so far. Is it possible that there is NO WAY to make concurrent calls from different threads to an external program? Because it seems to me that this would be one of the first examples of usage of multi-thread coding. I am using linux (mandriva) and the external program I wish to call can be called in different shells at the same time. I am not new to C++ but am new to multi-threading , so I would greatly appreciate any advice on the subject. Marcelo

推荐答案

是什么让您认为popen,system和fork是线程不安全的?来自fork手册页的引言:

What makes you think that popen, system and fork are thread-unsafe? A quote from the man page on fork:

子进程是通过单个线程创建的- 称为fork().父级的整个虚拟地址空间为 复制到子级中,包括互斥体的状态, 条件变量和其他pthreads对象;指某东西的用途 pthread_atfork(3)可能有助于解决此问题 会造成的.

The child process is created with a single thread — the one that called fork(). The entire virtual address space of the parent is replicated in the child, including the states of mutexes, condition variables, and other pthreads objects; the use of pthread_atfork(3) may be helpful for dealing with problems that this can cause.

如果调用system,则线程将阻塞,直到子进程退出.如果要并行启动多个外部命令,则只需启动10个调用系统的线程即可.

If you call system your thread will block until the child process exits. If you want to launch multiple external commands in parallel you can just start 10 threads which call system.

这篇关于在C ++中对外部命令的线程安全并发调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆