互斥锁(加锁和解锁操作)

来源:互联网 发布:天互数据在哪 编辑:程序博客网 时间:2024/05/16 06:08
#include<stdio.h>#include<stdlib.h>#include<string.h>#include<unistd.h>#include<sys/types.h>#include<pthread.h>/* 互斥锁 */unsigned int value1, value2, count;pthread_mutex_t mutex;void *fun(void *arg);int main(){    pthread_t thread;    if (0 > pthread_mutex_init(&mutex, NULL)) // 初始化    {        perror("pthread_mutex_init");        exit(-1);    }    if (0 > pthread_create(&thread, NULL, fun, NULL))    {        perror("pthread_create");        exit(-1);    }    while(1)    {        count++;    #if 1        pthread_mutex_lock(&mutex);// 加锁    #endif        value1 = count;        value2 = count;    #if 1        pthread_mutex_unlock(&mutex);// 解锁    #endif    }    return 0;}void *fun(void *arg){    while(1)    {    #if 1        pthread_mutex_lock(&mutex);    #endif        if (value1 != value2)        {            printf("count = %d,value1 = %d value2 = %d\n", count, value1, value2);            usleep(100000);        }    #if 1        pthread_mutex_unlock(&mutex);    #endif    }    return NULL;}

原创粉丝点击