线程级别的生命期。使用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在每个线程中,地址是独立的。

相关文章:

  • 2021-12-30
  • 2021-07-24
  • 2021-08-15
  • 2021-07-27
  • 2021-07-15
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2023-03-07
  • 2022-12-23
  • 2021-04-14
  • 2022-12-23
  • 2022-12-23
  • 2022-02-02
相关资源
相似解决方案