Linux编程:互斥锁实现共享资源访问

使用互斥锁实现共享资源访问 

能打印完整的hello world或者HELLO WORLD, 而不是hello和world分离

#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_mutex_t m;//定义互斥锁
 void err_thread(int ret,char *str)
{
	if(ret!=0)
	{
		fprintf(stderr,"%s:%s\n",str,strerror(ret));
		pthread_exit(NULL);
	}
}
void *tfn(void *arg)
{
	srand(time(NULL));
	while(1)
	{
		//加锁 m--
		pthread_mutex_lock(&m);
		printf("hello");
		printf("world!\n");
		//解锁 m++
		pthread_mutex_unlock(&m);
		sleep(rand()%3);	
	}
	return NULL;
}

int main(void)
{
	pthread_t tid;
	srand(time(NULL));
	int flag=5;
	//初始化mutex
	pthread_mutex_init(&m,NULL);
	//创建线程
	int ret = pthread_create(&tid,NULL,tfn,NULL);
	err_thread(ret,"pthread_create error");

	while(flag--)
	{
		//加锁 m--
		pthread_mutex_lock(&m);
		printf("HELLO");
		printf("WORLD!\n");
		//解锁 m++
		pthread_mutex_unlock(&m);
		sleep(rand()%3);
	}

	//取消线程
	pthread_cancel(tid);
	//等待线程终止
	pthread_join(tid,NULL);
	//销毁锁
	pthread_mutex_destroy(&m);
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值