wordpress网站 frp穿透,计算机专业学做网站吗,网站设计与制,百度云网盘免费资源C11 thread_local
thread_local 是 C11 中引入的关键字#xff0c;用于声明线程局部存储变量。线程局部存储变量是一种在每个线程中都有其自己的独立实例的变量。每个线程都可以独立地访问和修改其线程局部存储变量#xff0c;而不会影响其他线程的对应变量。
使用 thread_…C11 thread_local
thread_local 是 C11 中引入的关键字用于声明线程局部存储变量。线程局部存储变量是一种在每个线程中都有其自己的独立实例的变量。每个线程都可以独立地访问和修改其线程局部存储变量而不会影响其他线程的对应变量。
使用 thread_local 关键字声明的变量其生命周期与所属线程的生命周期相同。当线程终止时与其相关的 thread_local 变量也会被销毁。
测试代码
#include iostream
#include thread
#include unistd.h
#include mutex// 声明一个线程局部存储变量
thread_local int threadLocalVariable 0;
std::mutex mutex;void threadFunction(int num)
{// 在线程函数中访问线程局部存储变量for (int i 0; i 3; i){threadLocalVariable num;{std::lock_guardstd::mutex guard(mutex); std::cout Thread [ num ]: threadLocalVariable std::endl;}sleep(1);}
}int main()
{threadLocalVariable 10;// 创建两个线程std::thread t1(threadFunction, 1);std::thread t2(threadFunction, 2);std::thread t3(threadFunction, 3);// 等待线程结束t1.join();t2.join();t3.join();// 主线程中访问线程局部存储变量std::cout Thread [master]: threadLocalVariable std::endl;return 0;
}
代码输出
···log $ ./main Thread [1]: 1 Thread [2]: 2 Thread [3]: 3 Thread [1]: 2 Thread [2]: 4 Thread [3]: 6 Thread [1]: 3 Thread [2]: 6 Thread [3]: 9 Thread [master]: 10 ···
mutex防止多线程同时输出和测试内容无关。