在Linux多线程编程中,局部变量是指在函数内部定义的变量,其作用域仅限于该函数内部。以下是关于Linux线程局部变量的详细解释:
__thread
关键字(在GCC中)或thread_local
关键字(在C++11及以后标准中)声明。__thread
或thread_local
声明,存储在TLS中。__thread
关键字(GCC)#include <stdio.h>
#include <pthread.h>
__thread int thread_local_var = 0;
void* thread_func(void* arg) {
thread_local_var++;
printf("Thread ID: %ld, Local Var: %d
", pthread_self(), thread_local_var);
return NULL;
}
int main() {
pthread_t threads[5];
for (int i = 0; i < 5; ++i) {
pthread_create(&threads[i], NULL, thread_func, NULL);
}
for (int i = 0; i < 5; ++i) {
pthread_join(threads[i], NULL);
}
return 0;
}
thread_local
关键字(C++11)#include <iostream>
#include <thread>
thread_local int thread_local_var = 0;
void thread_func() {
thread_local_var++;
std::cout << "Thread ID: " << std::this_thread::get_id() << ", Local Var: " << thread_local_var << std::endl;
}
int main() {
std::thread threads[5];
for (int i = 0; i < 5; ++i) {
threads[i] = std::thread(thread_func);
}
for (auto& th : threads) {
th.join();
}
return 0;
}
通过合理使用线程局部变量,可以有效提高多线程程序的性能和安全性。
领取专属 10元无门槛券
手把手带您无忧上云