【发布时间】:2012-10-11 15:32:47
【问题描述】:
我正在编写一个小型实用程序,它应该使用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() 实例。
谢谢
【问题讨论】:
-
请粘贴更多代码!
标签: c++ multithreading c++11 thread-safety