Threadの使い方
C++ std11で追加されたThreadの使い方。
std::threadで関数、関数オブジェクトを渡せば、その関数を別スレッドで実行してくれる。
終わった後にdetachやjoinをしておかないと、コアダンプしてしまう。
下の例では、無名関数オブジェクトを作って渡している。
//test.cpp // $ g++ -std=c++14 -pthread test.cpp #include <iostream> #include <thread> class Cell { int _id; public: Cell(int id) { _id = id; } void run(void) { std::thread cellThread([&]{ while(1){ std::cout << "Cell Thread : " << _id << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); } }); cellThread.detach(); } }; int main() { std::cout << "Hello test.cpp" << std::endl; Cell *c1 = new Cell(1); Cell *c2 = new Cell(2); Cell *c3 = new Cell(3); c1->run(); c2->run(); c3->run(); while(1){ std::cout << "main loop : " << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); } }