Linux下的C语言开发(线程互斥)
来源:互联网 发布:淘宝导航怎么设置颜色 编辑:程序博客网 时间:2024/09/21 09:27
对于编写多线程的朋友来说,线程互斥是少不了的。在linux下面,编写多线程常用的工具其实是pthread_mutex_t。本质上来说,它和Windows下面的mutex其实是一样的,差别几乎是没有。
#include <stdio.h>#include <pthread.h>#include <unistd.h>#include <stdlib.h>static int value = 0;pthread_mutex_t mutex;void func(void* args){ while(1) { pthread_mutex_lock(&mutex); sleep(1); value ++; printf("value = %d!\n", value); pthread_mutex_unlock(&mutex); }}int main(){ pthread_t pid1, pid2; pthread_mutex_init(&mutex, NULL); if(pthread_create(&pid1, NULL, func, NULL)) { return -1; } if(pthread_create(&pid2, NULL, func, NULL)) { return -1; } while(1) sleep(0); return 0;}
编写mutex.c文件结束之后,我们就可以开始编译了。首先你需要输入gcc mutex.c -o mutex -lpthread,编译之后你就可以看到mutex可执行文件,输入./mutex即可。
[test@localhost thread]$ ./mutexvalue = 1!value = 2!value = 3!value = 4!value = 5!value = 6!
0 0
- linux下的C语言开发(线程互斥)
- linux下的C语言开发(线程互斥)
- linux下的C语言开发(线程互斥)
- linux下的C语言开发(线程互斥)
- linux下的C语言开发(线程互斥)
- Linux下的C语言开发(线程互斥)
- Linux下C语言多线程(第二篇)线程互斥pthread_mutex_t()
- linux 下线程的互斥
- Linux环境下线程的互斥
- linux下的C语言开发(线程等待)
- linux下的C语言开发(线程等待)
- linux下的C语言开发(线程等待)
- linux下的C语言开发(线程等待)
- linux下的C语言开发(线程等待)
- linux下的C语言开发(线程等待)
- linux下的C语言开发(线程等待)
- linux c 线程互斥
- linux c 线程互斥
- 数据库事物ACID特性和分布式系统CAP理论
- 浅谈Java并发编程系列(五)—— ReentrantLock VS synchronized
- 教自己学Python(三)练手小游戏:不要猜中
- NGINX学习
- <LeetCode>136. Single Number
- Linux下的C语言开发(线程互斥)
- 内存递归生成树形结构
- 前缀式计算
- 嵌入式linux启动后的初始化操作
- 299. Bulls and Cows
- InitSystemFunctions
- 学习新知识三大技能
- String类
- 合并两个有序数组为一个有序数组