c++ - 在 C++ std::vector 之外的线程中启动可运行对象

标签 c++ multithreading c++11 vector stdthread

我有一个 C++11 程序,它配置了许多可运行的对象,将它们放在 std::vector 中,然后在单独的线程中启动它们。不幸的是,当我遍历 vector 中的对象时,我只会为最后一个对象启动线程。我在以下测试代码中提炼了问题的核心(在 OSX 10.9.5 上使用 clang 6.0 使用 clang++ -std=c++11 cpp_threadlaunch.cpp 编译) ).

#include <iostream>
#include <thread>
#include <vector>
#include <unistd.h>

std::mutex  outputlock;

class agent {

public:
    agent(std::string name) : m_name(name) {};
    ~agent(void) {};

    void run(void) {
        while (1) {
            outputlock.lock();
            std::cout << "Agent: " << m_name << std::endl;
            outputlock.unlock();
            sleep(1);
        }
    }
    std::string     getName(void) { return m_name; }

private:

    std::string     m_name;
};

int main()
{
    std::vector<std::thread>        threads;
    std::vector<agent*>             agents;
    // std::string                  goal = "succeed";
    std::string                     goal = "fail";

    agents.push_back(new agent("A"));
    agents.push_back(new agent("B"));

    if (goal == "succeed") {

        threads.push_back(std::thread([&]() { agents.at(0)->run(); }));
        threads.push_back(std::thread([&]() { agents.at(1)->run(); }));

    }
    else {

        for (auto it = agents.begin(); it != agents.end(); it++) {

            agent* a = *it;

            std::cout << "Launching thread for " << a->getName() << std::endl;

            threads.push_back(std::thread([&]() { a->run(); }));
        }
    }

    for (auto it = threads.begin(); it != threads.end(); it++) {

        it->join();
    }

    exit(0);
}

当我以 goal = "succeed" 运行时,我得到了希望的输出

Agent: A
Agent: B
Agent: A
Agent: B

当我使用 goal = "fail" 运行时,我只从一个对象获得了输出的两份拷贝,而不是从每个对象获得输出:

Launching thread for A
Launching thread for B
Agent: B
Agent: B
Agent: B
Agent: B

我怀疑我在这里遗漏了一些基本的东西——如果有人能解释发生了什么以及解决方案是什么,我将不胜感激。谢谢——

最佳答案

您在循环中传递给 std::thread 的 lambda 函数通过引用捕获 a。由于 a 然后超出范围,您有未定义的行为。按值捕获它(使用 [=] 而不是 [&])。

关于c++ - 在 C++ std::vector 之外的线程中启动可运行对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34213183/

相关文章:

C++ 成员函数指针定义

c++ - 用圆形和三角形设计形状类

c++命令行宏预处理器无法替换单词

c - __sync_bool_compare_and_swap 不工作

c++ - 在 boost::mutex 构造函数中同时写入同一内​​存区域可能存在错误

python - 我可以从 Python 中的线程导入模块吗?

c++ - 具有特定参数的特定构造函数的类型声明

c++ - C++ 中的隐式静态变量?

c++ - WSARecv Hook : prevent packet from being recieved by the executable

c++ - 如何实现我的自定义范围 for 循环?