当前位置:天才代写 > tutorial > C语言/C++ 教程 > Linux下C编程:线程互斥实例

Linux下C编程:线程互斥实例

2017-11-02 08:00 星期四 所属: C语言/C++ 教程 浏览:472

/*编译时留意,要手动毗连库*/ 
#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(&pid2,NULL,&func,NULL))       
    {       
        return -1;       
    }       
          
    if(pthread_create(&pid1,NULL,&func,NULL))       
    {       
        return -1;       
    }       
    while(1)       
        sleep(0);       
          
    return 0;       
}

编译时要手动毗连库:具体说明见:http://blog.csdn.net/muge0913/article/details/7340126

查察全套文章:http://www.bianceng.cn/Programming/C/201212/34807.htm

 

    关键字:

天才代写-代写联系方式