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
    评论
Linux中,互斥锁是一种用于多线程编程的同步机制,用于保护共享资源,防止多个线程同时访问导致数据不一致或竞争条件的发生。Linux提供了几种互斥锁实现,其中最常见的是pthread库提供的互斥锁互斥锁的基本操作包括加锁(lock)和解锁(unlock)。当一个线程需要访问共享资源时,它首先尝试加锁,如果加锁成功,则可以安全地访问共享资源;如果加锁失败,线程会被阻塞,直到锁被释放为止。解锁操作用于释放互斥锁,使得其他线程可以获得锁并继续执行。 在Linux中,使用pthread库进行互斥锁的操作。下面是一个简单的示例代码: ```c #include <stdio.h> #include <pthread.h> pthread_mutex_t mutex; // 定义互斥锁 void* thread_func(void* arg) { // 加锁 pthread_mutex_lock(&mutex); // 访问共享资源 printf("Thread %d is accessing the shared resource.\n", *(int*)arg); // 解锁 pthread_mutex_unlock(&mutex); return NULL; } int main() { pthread_t tid[5]; int thread_args[5] = {1, 2, 3, 4, 5}; // 初始化互斥锁 pthread_mutex_init(&mutex, NULL); // 创建多个线程 for (int i = 0; i < 5; ++i) { pthread_create(&tid[i], NULL, thread_func, &thread_args[i]); } // 等待线程结束 for (int i = 0; i < 5; ++i) { pthread_join(tid[i], NULL); } // 销毁互斥锁 pthread_mutex_destroy(&mutex); return 0; } ``` 在上述示例代码中,我们首先定义了一个互斥锁`mutex`,然后在线程函数`thread_func`中对共享资源进行加锁和解锁操作。在主函数中,我们创建了5个线程,并等待它们结束后销毁互斥锁。 这只是互斥锁的基本使用方法,实际应用中可能还需要考虑一些高级的使用场景和技巧,如递归锁、条件变量等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值