C++ 多线程 读锁之后不能跟写锁 shared_lock之后不能跟unique_lock 死锁 解决方案
Posted 软件工程小施同学
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++ 多线程 读锁之后不能跟写锁 shared_lock之后不能跟unique_lock 死锁 解决方案相关的知识,希望对你有一定的参考价值。
#include <iostream>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
boost::shared_mutex mutex;
int count = 0;
void test(int j){
// boost::shared_lock<boost::shared_mutex> lock(mutex);
boost::unique_lock<boost::shared_mutex> lock(mutex);
std::cout << "test == " << j << std::endl;
}
void Counter() {
int i = count;
std::cout << "count == " << i << std::endl;
boost::shared_lock<boost::shared_mutex> lock(mutex);
test(count++);
}
int main() {
boost::thread_group threads;
for (int i = 0; i < 4; ++i) {
threads.create_thread(&Counter);
}
threads.join_all();
return 0;
}
写锁得等所有读锁释放之后,才能获得锁。可是每个子线程都持有读锁,并且不释放,所以造成死锁。
解决方案
用完锁就释放
#include <iostream>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
boost::shared_mutex mutex;
int count = 0;
void test(int j){
// boost::shared_lock<boost::shared_mutex> lock(mutex);
boost::unique_lock<boost::shared_mutex> lock(mutex);
std::cout << "test == " << j << std::endl;
}
void Counter() {
int i = count;
std::cout << "count == " << i << std::endl;
{
boost::shared_lock<boost::shared_mutex> lock(mutex);
}
test(count++);
}
int main() {
boost::thread_group threads;
for (int i = 0; i < 4; ++i) {
threads.create_thread(&Counter);
}
threads.join_all();
return 0;
}
以上是关于C++ 多线程 读锁之后不能跟写锁 shared_lock之后不能跟unique_lock 死锁 解决方案的主要内容,如果未能解决你的问题,请参考以下文章