1. 程式人生 > 其它 >C++11多執行緒(thread_local)

C++11多執行緒(thread_local)

thread_local 關鍵字修飾的變數具有執行緒(thread)週期,這些變數線上程開始的時候被生成,線上程結束的時候被銷燬,並且每一個執行緒都擁有一個獨立的變數例項。

thread_local 一般用於需要保證執行緒安全的函式中。

需要注意的一點是,如果類的成員函式內定義了 thread_local 變數,則對於同一個執行緒內的該類的多個物件都會共享一個變數例項,並且只會在第一次執行這個成員函式時初始化這個變數例項,這一點是跟類的靜態成員變數類似的。

case 1:

class A
{
public:
    A() {}
    ~A() {}

    void test(const
std::string &name) { thread_local int count = 0; ++count; std::cout << name.c_str() << ": " << count << std::endl; } }; void func(const std::string &name) { A a1; a1.test(name); a1.test(name); A a2; a2.test(name); a2.test(name); }
int main(int argc, char* argv[]) { std::thread t1(func, "t1"); std::thread t2(func, "t2"); t1.join(); t2.join(); return 0; }

輸出:

t1 : 1
t1 : 2
t1 : 3
t2 : 1
t2 : 2
t2 : 3
t2 : 4
t1 : 4

case 2:

class A
{
public:
    A() {}
    ~A() {}

    void test(const std::string &name)
    {
        
static int count = 0; ++count; std::cout << name.c_str() << ": " << count << std::endl; } }; void func(const std::string &name) { A a1; a1.test(name); a1.test(name); A a2; a2.test(name); a2.test(name); } int main(int argc, char* argv[]) { std::thread t1(func, "t1"); std::thread t2(func, "t2"); t1.join(); t2.join(); return 0; }

輸出:

t1: 1
t1: 3
t1: 4
t1: 5
t2: 2
t2: 6
t2: 7
t2: 8

轉載於:C++ 11 關鍵字:thread_local - 知乎 (zhihu.com)