生活随笔
收集整理的這篇文章主要介紹了
Linux互斥锁的使用代码实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
From: http://blog.csdn.net/leo115/article/details/8037869
[cpp] view plaincopy
#include?<stdio.h>??#include?<pthread.h>??#include?<sched.h>??#include?<unistd.h>????????void?*fun1(void?*arg);??void?*fun2(void?*arg);????int?buffer?=?0;??pthread_mutex_t?mutex;??int?running?=?1;????int?main(void?)??{??????pthread_t?pt1;??????pthread_t?pt2;????????pthread_mutex_init(&mutex,NULL);????????pthread_create(&pt1,NULL,fun1,(void*)&running);??????pthread_create(&pt2,NULL,fun2,(void*)&running);????????usleep(1000);??????running=0;??????pthread_join(pt1,NULL);??????pthread_join(pt2,NULL);??????pthread_mutex_destroy(&mutex);??????return?0;??}????void?*fun1(void?*arg)??{??????while(*(int?*)arg)??????{????????????????pthread_mutex_lock(&mutex);??????????printf("in?fun1?before?add?,?buffer?is?:?%d\n",buffer);??????????usleep(2);??????????buffer++;??????????printf("in?fun1?after?sleep?and?add?one?,now?buffer?is?%d?\n",buffer);????????????????pthread_mutex_unlock(&mutex);??????????usleep(2);??????}??}????void?*fun2(void?*arg)??{??????while(*(int?*)arg)??????{????????????????pthread_mutex_lock(&mutex);??????????printf("in?fun2?before?add?,?buffer?is?:?%d\n",buffer);??????????usleep(2);??????????buffer++;??????????printf("in?fun2?after?sleep?and?add?one?,now?buffer?is?%d?\n",buffer);????????????????pthread_mutex_unlock(&mutex);??????????usleep(2);??????}????}??
注釋互斥鎖前的運行結果:
注釋互斥鎖后的運行結果:
總結
以上是生活随笔為你收集整理的Linux互斥锁的使用代码实现的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。