[英]What is the equivalent of boost::upgrade_to_unique_lock in STL?
I'm trying to replace the boost functionalities with STL functinoalities in C++11. 我正在尝试用C ++ 11中的STL功能替换boost功能。 There is a write function in my multi-thread application.
我的多线程应用程序中有一个写入功能。
First, the function verifies the data. 首先,该功能验证数据。 Next, writes to it.
接下来,对其进行写入。 There are two locks mentioned as mentioned below:
提到了两个锁,如下所述:
class Data
{
mutable boost::mutex mut;
void Data::Write()
{
boost::upgrade_lock<boost::shared_mutex> ulock(mut);
// ... Verification statements
boost::upgrade_to_unique_lock<boost::shared_mutex> lock(ulock);
// ... Writing statements
}
};
I'm a novice of boost functionalities. 我是Boost功能的新手。 Can you please explain what it does and how I can achieve the functionality with STL features?
您能否解释一下它的作用以及如何使用STL功能实现该功能?
C++11 doesn't provide shared locks at all. C ++ 11根本不提供共享锁。 C++14 does, but doesn't allow them to be upgraded to exclusive locks;
C ++ 14可以,但是不允许将它们升级为排他锁; you'd need a second mutex for that, something like:
您需要第二个互斥锁,例如:
mutable std::shared_timed_mutex read_mutex;
std::mutex write_mutex;
void Write() {
std::shared_lock read_lock(read_mutex);
// ... Verification statements
std::lock_guard write_lock(write_mutex);
// ... Writing statements
}
You'll need to take some care only to acquire the write lock while already holding the read lock, to avoid deadlocks. 您只需要在已经持有读锁的同时获得写锁就可以避免死锁。 If you have a working Boost solution, it might be better to stick to that until the standard library provides equivalent functionality.
如果您具有有效的Boost解决方案,则最好坚持使用该方法,直到标准库提供等效的功能为止。
In C++ threads you get: 在C ++线程中,您得到:
#include <thread>
#include <mutex>
using namespace std;
mutex mu;
// lock_guard: acquire the mutex mu and lock it. when the lock_guard object goes out of scope, mutex is unlocked.
lock_guard<mutex> lock(mu);
// more flexible than the lock_guard
// http://en.cppreference.com/w/cpp/thread/unique_lock
unique_lock<mutex> ulock(mu);
ulock.unlock();
ulock.lock();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.