线程私有关键字配合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\n",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;
}


运行结果


posted on 2017-08-28 11:26  cfzhang  阅读(181)  评论(0)    收藏  举报

导航