linux下的C语言开发(线程互斥)

来源:互联网 发布:根据小说改编的网络剧 编辑:程序博客网 时间:2024/04/30 03:42

对于编写多线程的朋友来说,线程互斥是少不了的。在linux下面,编写多线程常用的工具其实是pthread_mutex_t。本质上来说,它和Windows下面的mutex其实是一样的,差别几乎是没有。希望对线程互斥进行详细了解的朋友可以看这里。

[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3. #include <unistd.h>  
  4. #include <stdlib.h>  
  5.   
  6. static int value = 0;  
  7. pthread_mutex_t mutex;  
  8.   
  9. void func(void* args)  
  10. {  
  11.     while(1)  
  12.     {  
  13.         pthread_mutex_lock(&mutex);  
  14.         sleep(1);  
  15.         value ++;  
  16.         printf("value = %d!\n", value);  
  17.         pthread_mutex_unlock(&mutex);  
  18.     }  
  19. }  
  20.   
  21. int main()  
  22. {  
  23.     pthread_t pid1, pid2;  
  24.     pthread_mutex_init(&mutex, NULL);  
  25.   
  26.     if(pthread_create(&pid1, NULL, func, NULL))  
  27.     {  
  28.         return -1;  
  29.     }  
  30.   
  31.     if(pthread_create(&pid2, NULL, func, NULL))  
  32.     {  
  33.         return -1;  
  34.     }  
  35.   
  36.     while(1)  
  37.         sleep(0);  
  38.   
  39.     return 0;  
  40. }  
    编写mutex.c文件结束之后,我们就可以开始编译了。首先你需要输入gcc mutex.c -o mutex -lpthread,编译之后你就可以看到mutex可执行文件,输入./mutex即可。
[cpp] view plaincopy
  1. [test@localhost thread]$ ./mutex  
  2. value = 1!  
  3. value = 2!  
  4. value = 3!  
  5. value = 4!  
  6. value = 5!  
  7. value = 6!  

原创粉丝点击