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