C++11 std::thread
今天來學習一下C++11的thread,直接貼上範例
thread 分為下列兩種
- join
- detach
join()會等待執行續執行完畢才繼續往下執行,detach 則反之。
thread 分為下列兩種
- join
- detach
join()會等待執行續執行完畢才繼續往下執行,detach 則反之。
#include <iostream> #include <thread> using namespace std; void func_count(const char *str, int &count) { for (int i = 0; i < 3; i++) { count++; printf("%s n=%d\n", str, count); } } int main() { int count1 = 0; int count2 = 0; int count3 = 0; thread t1(func_count, "thread1", ref(count1)); thread t2(func_count, "thread2", ref(count2)); thread t3(func_count, "thread3", ref(count3)); printf("main thread, conunt1=%d, conunt2=%d, conunt3=%d\n", count1, count2, count3); t1.join(); // wait for t1 thread t2.join(); // wait for t2 thread t3.detach(); // no wait for t3 thread return 0; }
留言
張貼留言