Chinaunix首页 | 论坛 | 博客
  • 博客访问: 117118
  • 博文数量: 61
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 230
  • 用 户 组: 普通用户
  • 注册时间: 2014-04-26 11:35
个人简介

实践Linux的理论

文章存档

2015年(1)

2014年(60)

我的朋友

分类: C/C++

2014-04-29 21:21:34

 对于编写多线程的朋友来说,线程互斥是少不了的。在linux下面,编写多线程常用的工具其实是pthread_mutex_t。本质上来说,它和Windows下面的mutex其实是一样的,差别几乎是没有。希望对线程互斥进行详细了解的朋友可以看这里。
[cpp] view plaincopy
#include  
#include  
#include  
#include  
  
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即可。
[cpp] view plaincopy
[test@localhost thread]$ ./mutex  
value = 1!  
value = 2!  
value = 3!  
value = 4!  
value = 5!  
value = 6!  

阅读(606) | 评论(0) | 转发(0) |
0

上一篇:ubuntu 12.04 安装wps

下一篇:线程等待

给主人留下些什么吧!~~