【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing @163.com】
对于编写多线程的朋友来说,线程互斥是少不了的。在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]$ ./mutex value = 1! value = 2! value = 3! value = 4! value = 5! value = 6!