【06并发程序设计】互斥锁的概念及使用

互斥锁的概念和使用

临界资源:只允许一个任务访问的资源。

例如外设打印机,打印的时候只能由一个程序使用。

mutex互斥锁:用来访问临界资源。

任务访问资源前申请锁,访问完后释放锁。

举例:(无互斥锁)

代码讲解:

代码中有两个线程会无限循环地向同一个文件(1.txt)写入内容。但这两个线程都在没有同步的情况下写入同一个文件,所以会遇到数据交错的问题,即一个线程写入的内容可能会被另一个线程写入的内容打断。

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

// pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

FILE *fp;
void *func2(void *arg){
	pthread_detach(pthread_self());
	printf("This func2 thread\n");

	char str[]="I write func2 line\n";

	char c;
	int i=0;
	while(1){

		// pthread_mutex_lock(&mutex);

		while(i<strlen(str)){
			c = str[i];
			fputc(c, fp);
			usleep(1);
			i++;
		}
		// pthread_mutex_unlock(&mutex);

		i=0;
		usleep(1);
	}
	pthread_exit("func2 exit");

}

void *func(void *arg){
	pthread_detach(pthread_self());
	printf("This is func1 thread\n");
	char str[]="You read func1 thread\n";
	char c;
	int i=0;
	while(1){

		// pthread_mutex_lock(&mutex);
		while(i<strlen(str)){
			c = str[i];
			fputc(c, fp);
			usleep(1);
			i++;

		}
		// pthread_mutex_unlock(&mutex);
		i=0;                                                                                       
		usleep(1);
	}

	pthread_exit("func1 exit");
}

int main(){
	pthread_t tid,tid2;
	void *retv;
	int i;
	fp = fopen("1.txt", "a+");
	if(fp==NULL){
		perror("fopen");
		return 0;
	}

	pthread_create(&tid2, NULL, func2, NULL);
	pthread_create(&tid, NULL, func, NULL);

	while(1){    
		sleep(1);
	} 
}

结果:

无互斥锁

在这里插入图片描述

有互斥锁结果(将代码中注释部分取消即可)

在这里插入图片描述

  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值