c++ - cpp 为什么 boost::thread inside for loop 没有遍历所有值并且正在推送相同的值?

标签 c++ multithreading bash boost

我正在尝试使用 boost::threadcommand 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/

相关文章:

c++ - 检查类/结构是否有特定的运算符

c++ - 递归斐波那契数列

c - 我如何跟踪所有 fork()

python - 如何在带有 moveToThread() 的 pyqt 中正确使用 QThread?

linux - 重命名子目录中的文件会删除文件

c++ - 我可以在 windows visual studio 中编写 C++ 或任何代码,然后将 'import' 写入 Linux 吗?

c++ - Visual Studio 错误 LNK2001 : unresolved external symbol _fgetc_unlocked

c# - System.Threading.Timer 回调永远不会被调用

bash - Azure DevOps 在 bash 任务内生成密码

bash - 有没有办法在Azure Pipeline中提取bash脚本的输出