线程私有关键字配合static使用

#include<stdio.h>
#include<pthread.h>

void* test(void *arg)
{
int n = 10;
static __thread int a = 0;
printf("running in thread :%d, a= %d ",pthread_self(),a++);
usleep(200);
}

void* test1(void *arg)
{
int n = 10;
while(n--)
test(NULL);
}
int main()
{
pthread_t thread1;
pthread_t thread2;
pthread_create(&thread1, NULL, test1, NULL);
pthread_create(&thread2, NULL, test1, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}


运行结果


原文地址:https://www.cnblogs.com/cfzhang/p/8748d0e4ca39c7246750547bcbd17f5e.html