我正在编写一个小实用程序,它应该使用 system()
并行启动多个命令,并等待它们的结果用于记录目的。但是,即使我在不同的线程上调用 system()
,通过查看我的事件监视器,我一次也只能看到每个命令的一个实例。看起来系统在互斥量上是内部同步的,每次只允许执行一次,但这看起来是一个巨大的限制,有人可以确认这种行为吗?您对如何解决它有任何想法吗?
更新 通过查看线程执行流程,看起来它们在互斥锁上有效同步。是否有替代的 system()
不这样做?
我应该提到我在 Mac OS 10.7.5 上使用 C++11(w/clang 和 libc++)。
更新代码为:
void Batch::run()
{
done.clear();
generator->resetGeneration();
while(generator->hasMoreParameters())
{
// Lock for accessing active
unique_lock<mutex> lock(q_mutex, adopt_lock);
// If we've less experiments than threads
if (active.size() < threads)
{
Configuration conf = generator->generateParameters();
Experiment e(executable, conf);
thread t(&Experiment::run, e, reference_wrapper<Batch>(*this));
thread::id id = t.get_id();
active.insert(id);
t.detach();
}
// Condition variable
q_control.wait(lock, [this] { return active.size() < threads; } );
}
}
void Batch::experimentFinished(std::thread::id pos)
{
unique_lock<mutex> lock(q_mutex, adopt_lock);
active.erase(pos);
lock.unlock();
q_control.notify_all();
}
void Experiment::run(Batch& caller)
{
// Generate run command
stringstream run_command;
run_command << executable + " ";
ParameterExpression::printCommandLine(run_command, config);
if (system(run_command.str().c_str()))
stats["success"] = "true";
else
stats["success"] = "false";
caller.experimentFinished(this_thread::get_id());
}
需要说明的是:线程的生成和处理工作正常并且完成了它需要做的事情,但看起来您一次只能运行一个 system()
实例。
谢谢
最佳答案
POSIX 对 system(3)
有这样的说法:
Using the system() function in more than one thread in a process or when the SIGCHLD signal is being manipulated by more than one thread in a process may produce unexpected results.
由于在执行期间必须阻止 SIGCHLD 的方式,并发运行 system
调用实际上不起作用。如果你想让多线程运行外部任务,你需要多写一点代码(自己处理fork
/exec
/wait
) .
关于c++ - C++的system()是同步的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12843274/