c++ thread_local
测试代码:
thread_local int thread_localVal = 0; // 关键字thread_local修饰线程局部变量void increase(int increaseVal) {thread_localVal += increaseVal;std::cout << "thread_localVal: " << thread_localVal << " , current thread id: " << std::this_thread::get_id() << endl;
}void testThreadLocal() { // 测试代码std::thread t1(increase, 250);t1.join();std::thread t2(increase, 9527);t2.join();std::cout << "===========" << std::endl;thread_localVal += 1605;std::cout << "thread_localVal: " << thread_localVal << " , current thread id: " << std::this_thread::get_id() << endl;
}
打印:
ok. 可以看出, thread_local修饰的变量为线程局部变量,该变量在线程间是独立的。