找回密码
 用户注册

QQ登录

只需一步,快速开始

查看: 3364|回复: 0

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

[复制链接]
发表于 2012-2-8 22:33:16 | 显示全部楼层 |阅读模式
    对于编写多线程的朋友来说,线程互斥是少不了的。在linux下面,编写多线程常用的工具其实是pthread_mutex_t。本质上来说,它和Windows下面的mutex其实是一样的,差别几乎是没有。希望对线程互斥进行详细了解的朋友可以看这里
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <unistd.h>
  4. #include <stdlib.h>
  5. static int value = 0;
  6. pthread_mutex_t mutex;
  7. void func(void* args)
  8. {
  9.     while(1)
  10.     {
  11.         pthread_mutex_lock(&mutex);
  12.         sleep(1);
  13.         value ++;
  14.         printf("value = %d!\n", value);
  15.         pthread_mutex_lock(&mutex);
  16.     }
  17. }
  18. int main()
  19. {
  20.     pthread_t pid1, pid2;
  21.     pthread_mutex_init(&mutex, NULL);
  22.     if(pthread_create(&pid1, NULL, func, NULL))
  23.     {
  24.         return -1;
  25.     }
  26.     if(pthread_create(&pid2, NULL, func, NULL))
  27.     {
  28.         return -1;
  29.     }
  30.     while(1)
  31.         sleep(0);
  32.     return 0;
  33. }
复制代码
    编写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!

作者:feixiaoxing 发表于2012-2-8 21:39:04 原文链接

您需要登录后才可以回帖 登录 | 用户注册

本版积分规则

Archiver|手机版|小黑屋|ACE Developer ( 京ICP备06055248号 )

GMT+8, 2024-5-7 20:27 , Processed in 0.020062 second(s), 6 queries , Redis On.

Powered by Discuz! X3.5

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表