#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;
}
?
?
|