码迷,mamicode.com
首页 > 系统相关 > 详细

linux 互斥锁

时间:2019-02-24 15:01:22      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:线程   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 }

 

linux 互斥锁

标签:线程   mutex   pre   std   lib   ini   main   include   nbsp   

原文地址:https://www.cnblogs.com/libing029/p/10426160.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!