Linux互斥锁的使用代码实现
来源:互联网 发布:手机qq软件 编辑:程序博客网 时间:2024/05/11 00:30
From: http://blog.csdn.net/leo115/article/details/8037869
- #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);
- }
- }
注释互斥锁前的运行结果:
注释互斥锁后的运行结果:
- Linux互斥锁的使用代码实现
- Linux互斥锁的使用代码实现
- 代码实现LDT的使用
- Linux下使用Shell脚本实现ftp的自动上传下载的代码小结
- Linux下使用Shell脚本实现ftp的自动上传下载的代码小结 【转】
- Linux下Ping的实现代码
- linux基本的聊天软件代码实现
- 群聊程序的linux代码实现
- linux 代码实现文件夹及其文件的
- linux下使用__FILE__,__LINE__,FUNCTION__实现代码跟踪调试
- Linux下完美使用find+grep实现全局代码搜索
- linux下使用C或C++实现进程管理代码
- linux环境下使用vim实现简易进度条代码
- 使用JSR234实现代码的缩放
- 使用jQuery操作Cookies的实现代码
- 不使用工厂模式的代码实现
- autolayout的使用原理及代码实现
- 使用MapReduce实现关系代数的代码
- JNI数据类型的详解
- 查看连接到SQL Server数据库的用户信息
- GDB中应该知道的几个调试方法
- 双连通分量
- 标准I/O库(对流的操作)
- Linux互斥锁的使用代码实现
- 创建文件夹问题
- Asp 导出Excel
- Shell中的>/dev/null 2>&1 与 2>&1 >/dev/null 与&>/dev/null 的区别
- 找工作笔试面试补充基础知识(1)---内存对齐
- android的jni使用方法的一些探索和研究
- 页面置换算法
- 百度与谷歌搜索结果差异
- 【推荐】JAVA基础◆浅谈3DES加密解密