pthread_mutex_lock造成死锁原因

刚刚接触linux不久,在多线程编程时遇到了互斥锁死锁的情况,分析原因是同一个锁连续两次加锁,导致程序被锁死。
代码如下:
void f(void)
{
	...
	pthread_mutex_lock(&mutex);
	共用变量a 
	pthread_mutex_unlock(&mutex);
	...
}

void rt1(void)
{
	while(1)
	{
		pthread_mutex_lock(&mutex);
		...
		共用变量a
		...
		f();
		pthread_mutex_unlock(&mutex);
	}
}
避免这种情况的方法是,尽量在线程中加锁/解锁,尽可能不再函数中使用 pthread_mutex_lock。

`pthread_mutex_trylock` 函数用于尝试对一个互斥锁进行加锁,如果该锁当前没有被其他线程占用,则加锁成功,返回0;否则,加锁失败,返回EBUSY。其函数原型如下: ```c #include <pthread.h> int pthread_mutex_trylock(pthread_mutex_t *mutex); ``` 其中,`mutex` 参数是指向互斥锁变量的指针。 使用 `pthread_mutex_trylock` 时需要注意以下几点: 1. 确保互斥锁已经被初始化,否则加锁行为是未定义的。 2. 如果一个线程已经拥有了该互斥锁,再次尝试对该锁进行加锁会导致死锁。 3. 在加锁成功后,必须在合适的时候调用 `pthread_mutex_unlock` 函数对该锁进行解锁,否则会导致其他线程永远无法对该锁进行加锁。 下面是一个简单的示例程序: ```c #include <stdio.h> #include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* thread_func(void* arg) { int ret = pthread_mutex_trylock(&mutex); if (ret == 0) { printf("Thread %ld got the lock.\n", (long)arg); pthread_mutex_unlock(&mutex); } else { printf("Thread %ld failed to get the lock.\n", (long)arg); } return NULL; } int main() { pthread_t thread1, thread2; pthread_create(&thread1, NULL, thread_func, (void*)1); pthread_create(&thread2, NULL, thread_func, (void*)2); pthread_join(thread1, NULL); pthread_join(thread2, NULL); return 0; } ``` 该程序创建了两个线程分别尝试对互斥锁进行加锁。其中,一个线程能够成功获取到锁,另一个线程则失败。运行结果类似如下: ``` Thread 1 got the lock. Thread 2 failed to get the lock. ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值