死锁例子

引入了锁以后,其实也难免会造成一些问题,比如说忘记unlock,或者有两个锁a和b,一个锁a在等待锁b的解锁,锁b在等待锁a的解锁,这些情况都会造成程序的死锁,

比如下面这个例子: 

#include 
#include 
#include 

void work1(std::mutex& mylock1, std::mutex& mylock2) {
	for (int i = 0; i < 100000; i++) {
		mylock1.lock();
		mylock2.lock();
		std::cout << "work1 : " << i << std::endl;
		mylock2.unlock();
		mylock1.unlock();
	}
}

void work2(std::mutex& mylock1, std::mutex& mylock2) {
	for (int i = 0; i < 100000; i++) {
		mylock2.lock();
		mylock1.lock();
		std::cout << "work2 : " << i << std::endl;
		mylock1.unlock();
		mylock2.unlock();
	}
}

int main()
{
	std::mutex mylock1, mylock2;
	int ans = 0;
	std::thread t1(work1, std::ref(mylock1), std::ref(mylock2));
	std::thread t2(work2, std::ref(mylock1), std::ref(mylock2));
	t1.join();
	t2.join();
	return 0;
}

由于交叉加锁,使得两个锁都在等待对方解锁而造成的死锁,运行结果如下图所示:

运行结果

work2 : 0

work2 : 1

work2 : 2

work2 : 3

work2 : 4

work2 : 5

work2 : 6

work2 : 7

work2 : 8

work2 : 9

work1 : 0

work1 : 1

work1 : 2

work1 : 3

work1 : 4

work1 : 5

work1 : 6

.

.

.

work1 : 413

work1 : 414

work1 : 415

work1 : 416

后面就卡死了

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

解决这个死锁的问题只是把加锁的顺序改过来就可以了,然后也可以用std::lock函数来创建多个互斥锁,用法也很简单,首先创建两个互斥锁lock1和lock2,那么std::lock(lock1,lock2)这句代码就相当于lock1.lock();lock2.lock();,最后不要忘了对两个锁的unlock,其实也可以搭配lock_guard()来使用,因为lock_guard内部就有析构函数来unlock,所以在lock_guard中引用std::adopt_lock参数(作用是告诉编译器我已经lock过了,不需要再重复lock了)就可以实现省去后面的unlock语句了。代码如下:

#include 
#include 
#include 

void work1(std::mutex& mylock1, std::mutex& mylock2) 
{
	for (int i = 0; i < 100000; i++) 
    {
		std::lock(mylock1, mylock2);
		std::lock_guard lock1(mylock1, std::adopt_lock);
		std::lock_guard lock2(mylock2, std::adopt_lock);
		std::cout << "work1 : " << i << std::endl;
	}
}

void work2(std::mutex& mylock1, std::mutex& mylock2) {
	for (int i = 0; i < 100000; i++) {
		std::lock(mylock1, mylock2);
		std::lock_guard lock1(mylock1, std::adopt_lock);
		std::lock_guard lock2(mylock2, std::adopt_lock);
		std::cout << "work2 : " << i << std::endl;
	}
}

int main()
{
	std::mutex mylock1, mylock2;
	int ans = 0;
	std::thread t1(work1, std::ref(mylock1), std::ref(mylock2));
	std::thread t2(work2, std::ref(mylock1), std::ref(mylock2));
	t1.join();
	t2.join();
	return 0;
}

    

你可能感兴趣的:(死锁例子)