我正在尝试使用 boost::thread
在 command line
上运行 bash 脚本并行。
bash 脚本将 args 值写入日志文件。
for (unsigned int i = 0; i < count; i++) {
std::string nIndexLine = nIndex[i].line;
boost::thread z(CommandLineRun, nIndexLine);
}
void CommandLineRun(const std::string& Command)
{
int systemRet = system(Command.c_str());
if(systemRet == -1){
// The system method failed
}
}
上面的代码有效,但我看到了same entries multiple times
, 在 log file
. 。例如。如果nIndex
有 500 values
那么 nIndex[0]
的值在 log file
中被写入 500 次.
恕我直言,for 循环不会遍历所有条目。但是如果我删除 boost::thread
, 然后 for 循环按预期工作。
我做错了什么?
我不想要命令行的任何输出,我只希望它在命令行上运行命令。别再费心了。
更新:结果
boost::raplce_all
导致问题。就在boost::thread
之前
最佳答案
您的 CommandLineRun()
函数收到对字符串的引用,该字符串可能已更改,甚至在实际调用该函数时消失。
你应该试试这个:
for (unsigned int i = 0; i < count; i++)
{
boost::thread z(CommandLineRun, nIndex[i].line); // refer to the original string.
z.detach(); // making this explicit makes your intent clear
}
void CommandLineRun(std::string Command) // getting a copy of the string
{
int systemRet = system(Command.c_str());
if(systemRet == -1){
// The system method failed
}
}
关于c++ - cpp 为什么 boost::thread inside for loop 没有遍历所有值并且正在推送相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45655446/