线程同步之互斥量加锁解锁并且互斥锁限制共享资源的访问

概念
互斥量(mutex)从本质上来说是一把锁,在访问共享资源前对互斥量进行加锁,在访问完成后释放互斥量上的锁。对互斥量进行加锁后,任何其他试图再次对互斥量加锁的线程将会被阻塞直到当前线程释放该互斥锁。如果释放互斥锁时有多个线程阻塞,所有在该互斥锁上的阻塞线程都会变成可运行状态,第一个变为可运行状态的线程可以对互斥量加锁,其他线程将会看到互斥锁依然被锁住,只能回去等待它重新变为可用。在这种方式下,每次只有一个线程可以向前运行。
用法
第一步全局定义一个pthread_mutex_t类型

pthread_mutex_t mutex;

第二步在主函数创建及销毁互斥锁

#include <pthread.h>
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
int pthread_mutex_destroy(pthread_mutex_t mutex);
// 返回:若成功返回0,否则返回错误编号

第三步* 在相对应的线程需要操作的位置加锁及解锁*

int pthread_mutex_lock(pthread_mutex_t mutex);
int pthread_mutex_unlock(pthread_mutex_t mutex);
// 返回:若成功返回0,否则返回错误编号

例子:
如果不加锁的话两个线程间会争夺资源,互相输出
加锁后会运行完锁内的任务并且解锁才会执行其他线程的任务
运行的目的:使得fun1得到3就退出

#include<stdio.h>
#include<pthread.h>
int data = 0;
pthread_mutex_t mutex;

void *fun1(void *arg){
	
	printf("t1: %ld thread\n",(unsigned long)pthread_self());//将其id输出
	printf("param1 : %d\n",*((int *)arg));
	pthread_mutex_lock(&mutex);
	while(1){
		printf("t1: %d\n",data++);
		sleep(1);
		if (data == 3){
			pthread_mutex_unlock(&mutex);
			printf("=====t1 quit======\n");
			break;
		}
	}
}

void *fun2(void *arg){
	
	printf("t2: %ld thread\n",(unsigned long)pthread_self());//将其id输出
	printf("param2 : %d\n",*((int *)arg));
	while(1){
		pthread_mutex_lock(&mutex);
		printf("t2: %d\n",data++);
		sleep(1);
		pthread_mutex_unlock(&mutex);	
	}
}
int main(){
	int ret;
	int param = 100;
	pthread_mutex_init(&mutex,NULL);
	pthread_t t1;
	pthread_t t2;
	char *pret = NULL;
	ret = pthread_create(&t1,NULL,fun1,(void *)&param);//创建线程
	ret = pthread_create(&t2,NULL,fun2,(void *)&param);
	printf("main: %ld thread\n",(unsigned long)pthread_self());
	
	pthread_join(t1,NULL);	
	pthread_join(t2,NULL);	
	pthread_mutex_destroy(&mutex);
	return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值