打开APP
未登录
开通VIP,畅享免费电子书等14项超值服
开通VIP
首页
好书
留言交流
下载APP
联系客服
Linux互斥锁的使用代码实现
surfboarder
>《01A_Linux_C》
2017.07.25
关注
[cpp]
view plain
copy
#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);
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);
pthread_mutex_unlock(&mutex);
usleep(2);
}
}
void *fun2(void *arg)
{
while(*(int *)arg)
{
//pthread_mutex_lock(&mutex);
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);
pthread_mutex_unlock(&mutex);
usleep(2);
}
}
注释互斥锁前的运行结果:
注释互斥锁后的运行结果:
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报
。
打开APP,阅读全文并永久保存
查看更多类似文章
猜你喜欢
类似文章
【热】
打开小程序,算一算2024你的财运
Linux性能评测工具之一:gprof篇
Linux多线程编程小结
编程实现生产者消费者问题
200行C代码实现简单线程池 - Linux内核编程 - 举世无双的学习之路
Linux 线程池
linux下C实现多线程
更多类似文章 >>
生活服务
热点新闻
留言交流
回顶部
联系我们
分享
收藏
点击这里,查看已保存的文章
导长图
关注
一键复制
下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!
联系客服
微信登录中...
请勿关闭此页面
先别划走!
送你5元优惠券,购买VIP限时立减!
5
元
优惠券
优惠券还有
10:00
过期
马上使用
×