死锁的几种玩法
//
//一, 加锁顺序不当,下面这份代码首先线程1申请了mutex1锁,再去申请mutex2锁,有可能mutex2锁被线程2领走了,造成了线程1拿了mutex1再等mutex2,线程2拿了mutex2再等mutex1,循环等待造成死锁,正确方法是让两个线程都先拿mutex1再拿mutex2(下面代码演示)
//二, 连续加锁,比如 pthread_mutex_lock(&mutex1);pthread_mutex_lock(&mutex1);连续出现两次。
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t mutex1;
pthread_mutex_t mutex2;
int num = 0;
void* mythread1(void* argv) {
for (int i = 0; i < 10; i++) {
pthread_mutex_lock(&mutex1);
sleep(0.1);
pthread_mutex_lock(&mutex2);
num++;
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
}
}
void* mythread2(void* argv) {
for (int i = 0; i < 10; i++) {
pthread_mutex_lock(&mutex2);
sleep(0.1);
pthread_mutex_lock(&mutex1);
num++;
pthread_mutex_unlock(&mutex1);
pthread_mutex_unlock(&mutex2);
}
}
int main()
{
pthread_mutex_init(&mutex1, NULL);
pthread_mutex_init(&mutex2, NULL);
pthread_t thread1;
pthread_create(&thread1, NULL, mythread1, NULL);
pthread_t thread2;
pthread_create(&thread2, NULL, mythread2, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
if (num == 20) {
printf("wo mei you si suo!\n");
}
}
// 正确代码
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t mutex1;
pthread_mutex_t mutex2;
int num = 0;
void* mythread1(void* argv) {
for (int i = 0; i < 10; i++) {
pthread_mutex_lock(&mutex1);
sleep(0.1);
pthread_mutex_lock(&mutex2);
num++;
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
}
}
void* mythread2(void* argv) {
for (int i = 0; i < 10; i++) {
pthread_mutex_lock(&mutex1);
sleep(0.1);
pthread_mutex_lock(&mutex2);
num++;
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
}
}
int main()
{
pthread_mutex_init(&mutex1, NULL);
pthread_mutex_init(&mutex2, NULL);
pthread_t thread1;
pthread_create(&thread1, NULL, mythread1, NULL);
pthread_t thread2;
pthread_create(&thread2, NULL, mythread2, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
if (num == 20) {
printf("wo mei you si suo!\n");
}
}