C++11 std::thread

今天來學習一下C++11的thread,直接貼上範例
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;
}

留言

這個網誌中的熱門文章

4個免費線上筆記本

Android取经之路系列文章

[Chrome 外掛] Redirect Path 查看重定向的所有過程