C++ thread_local

线程级别的生命期。使用C++11引入的关键字thread_local.

#include <stdio.h>
#include <thread>
#include <mutex>

std::mutex mtx;

struct S
{
    S() {
        std::lock_guard<std::mutex> lock(mtx);
        printf("S() called i=%d\n", i);
    }
    int i = 0;
};

thread_local S gs;

void foo()
{
    std::lock_guard<std::mutex> lock(mtx);
    gs.i += 1;
    printf("foo  %p, %d\n", &gs, gs.i);
}

void bar()
{
    std::lock_guard<std::mutex> lock(mtx);
    gs.i += 2;
    printf("bar  %p, %d\n", &gs, gs.i);
}

int main()
{
    std::thread a(foo), b(foo);
    a.join();
    b.join();
}

最终结果,gs在每个线程中,地址是独立的。

posted @ 2018-03-26 12:13  thomas76  阅读(1387)  评论(0编辑  收藏  举报