I have a C ++ 11 program that configures several running objects, puts them in std::vector, and then runs them all in separate threads. Unfortunately, when I iterate over objects in a vector, I only start threads for the last object. I tried the problem in my kernel in the following test code (compiled clang++ -std=c++11 cpp_threadlaunch.cppwith using clang6.0 on OSX 10.9.5).
#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 = "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);
}
When I run with goal = "succeed", I get the expected output
Agent: A
Agent: B
Agent: A
Agent: B
When I run from goal = "fail", I get two copies of the output from only one object instead of the output from each object:
Launching thread for A
Launching thread for B
Agent: B
Agent: B
Agent: B
Agent: B
, - - , - , . -