互斥锁练习

创建一个进程,在主线程中创建一个子线程,主线程和子线程都会使用相同的临界资源(全局变量),要求线程之前使用互斥锁实现资源的互斥访问。

/*********************************************************************************
*
*
* func:使用互斥锁访问临界资源
* author:jindouliu2024@163.com 
* date:2025.5.8
* Copyright (c)  2024-2025   jindouliu2024@163.com   All right Reserved
* ********************************************************************************/

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int x = 10;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void * task1(void *arg)
{
	while(1){
		//上锁
		 pthread_mutex_lock(&mutex);
		 printf("x = %d\n",x);
		//解锁
		pthread_mutex_unlock(&mutex);
		sleep(2);
	}
		
}
int main()
{
	//初始化互斥锁
	pthread_mutex_init(&mutex,NULL);
	pthread_t task_1;
    //创建线程
    pthread_create(&task_1, NULL, task1, NULL); // 创建线程
	while(1){
		//上锁
		pthread_mutex_lock(&mutex);
		x += 2;
		//解锁
		pthread_mutex_unlock(&mutex);
		sleep(1);
	}
	

}
posted @ 2025-05-08 18:39  LRadian  阅读(78)  评论(0)    收藏  举报