C++11 thread_local

C++11 thread_local

c++11引入thread_local关键字,用thread_local修饰的变量具有thread周期,从属于访问它的线程,线程第一次访问它时创建它且只创建一次(与被static的修饰的变量是一样的,多实例共享一份),线程结束时系统释放该变量。简单点说就是变成在各自线程中static变量

#include <bits/stdc++.h>

class Thread_Local_A {
public:
    Thread_Local_A() {}

    ~Thread_Local_A() {}

    void add(const std::string &name) {
        thread_local int count = 0;
        ++count;
        std::cout << name << ": " << count << std::endl;
    }
};

void func(const std::string &name) {
    Thread_Local_A a1;
    a1.add(name);
    a1.add(name);
    Thread_Local_A a2;
    a2.add(name);
    a2.add(name);
}

thread_local int sum = 0;

void add(const std::string &name) {
    for (int i = 0; i < 10; ++i) {
        ++sum;
        std::cout << name << ": " << sum << std::endl;
    }
}

int main() {
    std::thread(add, "t1").join();
    std::thread(add, "t2").join();
    std::thread(func, "t3").join();
    std::thread(func, "t4").join();
    return 0;
}

输出:

t1: 1
t1: 2
t1: 3
t1: 4
t1: 5
t1: 6
t1: 7
t1: 8
t1: 9
t1: 10
t2: 1
t2: 2
t2: 3
t2: 4
t2: 5
t2: 6
t2: 7
t2: 8
t2: 9
t2: 10
t3: 1
t3: 2
t3: 3
t3: 4
t4: 1
t4: 2
t4: 3
t4: 4
posted @ 2022-02-20 13:26  DarkH  阅读(212)  评论(0编辑  收藏  举报