互斥锁:在主线程里面生成子线程,实现两个线程互斥访问临界资源


#include <stdio.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>


int x;      // 临界资源
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;


void *con_do(void *arg){
    while(1){
        pthread_mutex_lock(&mutex);       //加锁
        x = x + 1;
        pthread_mutex_unlock(&mutex);     //关锁
        sleep(3);
    }
}

int main(){
    x = 0;
    pthread_mutex_init(&mutex,NULL);    //初始化互斥锁锁

    pthread_t pid;
    if (pthread_create( &pid, NULL, con_do, NULL) != 0 ){
        perror("pthread_create failed");
        return 1;
    }

    while(1){
        pthread_mutex_lock(&mutex);       //加锁
        printf("%d\n",x);
        pthread_mutex_unlock(&mutex);     //关锁
        sleep(2);
    }
}
posted @ 2026-09-18 00:00    阅读(5)  评论(0)    收藏  举报