标签:线程 mutex pre std lib ini main include nbsp
1 #include<stdio.h> 2 #include<pthread.h> 3 #include<stdlib.h> 4 #include<unistd.h> 5 6 int num=0; 7 pthread_mutex_t lock; 8 pthread_t th; 9 10 11 void* th_handler(void* p){ 12 int i=0; 13 for(;i<10;i++){ 14 pthread_mutex_lock(&lock); 15 num++;17 printf("sub num=%d\n",num); 18 pthread_mutex_unlock(&lock); 19 sleep(1); 20 } 21 } 22 23 2425 int main(){ 26 27 pthread_mutex_init(&lock,NULL); 28 pthread_create(&th,NULL,th_handler,(void*)0);
//pthread_detach(th);设置分离线程不需要pthread_join();
29 sleep(1); 30 int i=0; 31 for(;i<10;i++){ 32 pthread_mutex_lock(&lock); 33 num++;35 printf("main num=%d\n",num); 36 pthread_mutex_unlock(&lock); 37 sleep(1); 38 } 39 pthread_mutex_destroy(&lock); 40 pthread_join(th,0); 41 42 }
标签:线程 mutex pre std lib ini main include nbsp
原文地址:https://www.cnblogs.com/libing029/p/10426160.html