C++ 多线程死锁(引入lock函数)

上一篇讲了互斥锁(传送门)的用法,解决了多线程共享资源可能会造成的一些问题,那么引入了锁以后,其实也难免会造成一些问题,比如说忘记unlock,或者有两个锁a和b,一个锁a在等待锁b的解锁,锁b在等待锁a的解锁,这些情况都会造成程序的死锁,比如下面这个例子:

#include <iostream>  #include <thread>  #include <mutex>    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;  }

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

       解决这个死锁的问题只是把加锁的顺序改过来就可以了,然后也可以用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 <iostream>  #include <thread>  #include <mutex>    void work1(std::mutex& mylock1, std::mutex& mylock2) {  	for (int i = 0; i < 100000; i++) {  		std::lock(mylock1, mylock2);  		std::lock_guard<std::mutex> lock1(mylock1, std::adopt_lock);  		std::lock_guard<std::mutex> 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<std::mutex> lock1(mylock1, std::adopt_lock);  		std::lock_guard<std::mutex> 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;  }