目前没有在线演示这一点的示例。在http://en.cppreference.com/w/cpp/header/shared_mutex看到了一个示例,但仍不清楚。可以有人帮忙吗?
目前没有在线演示这一点的示例。在http://en.cppreference.com/w/cpp/header/shared_mutex看到了一个示例,但仍不清楚。可以有人帮忙吗?
使用普通的互斥锁,可以保证对于某种关键资源的独占访问 - 除此之外没有其他访问。共享互斥锁通过允许两种级别的访问(共享和独占)来扩展此功能,如下所示:
一个典型的情况是数据库:如果几个线程同时读取相同的数据,则并不重要。但是修改数据库是关键的-如果某个线程读取数据而另一个线程正在写入,则可能会收到不一致的数据。因此,在允许写入之前,必须完成所有读取,并且必须等待写入完成后才能进行新的读取。写入后,进一步的读取可以再次同时发生。
编辑:旁注:
为什么读者需要锁?
这是为了防止在读取尚未完成时,写者获取该锁。此外,如果独占持有该锁,则会防止新读取程序获取该锁。
#include <iostream>
#include <mutex>
#include <shared_mutex>
#include <thread>
std::mutex cout_mutex;//Not really part of the example...
void log(const std::string& msg){
std::lock_guard guard(cout_mutex);
std::cout << msg << std::endl;
}
class ThreadSafeCounter {
public:
ThreadSafeCounter() = default;
// Multiple threads/readers can read the counter's value at the same time.
unsigned int get() const {
std::shared_lock lock(mutex_);//NB: std::shared_lock will shared_lock() the mutex.
log("get()-begin");
std::this_thread::sleep_for(std::chrono::milliseconds(500));
auto result=value_;
log("get()-end");
return result;
}
// Only one thread/writer can increment/write the counter's value.
void increment() {
std::unique_lock lock(mutex_);
value_++;
}
// Only one thread/writer can reset/write the counter's value.
void reset() {
std::unique_lock lock(mutex_);
value_ = 0;
}
private:
mutable std::shared_mutex mutex_;
unsigned int value_ = 0;
};
int main() {
ThreadSafeCounter counter;
auto increment_and_print = [&counter]() {
for (int i = 0; i < 3; i++) {
counter.increment();
auto ctr=counter.get();
{
std::lock_guard guard(cout_mutex);
std::cout << std::this_thread::get_id() << ' ' << ctr << '\n';
}
}
};
std::thread thread1(increment_and_print);
std::thread thread2(increment_and_print);
std::thread thread3(increment_and_print);
thread1.join();
thread2.join();
thread3.join();
}
get()-begin
get()-begin
get()-end
140361363867392 2
get()-end
140361372260096 2
get()-begin
get()-end
140361355474688 3
//Etc...
get()-begin()
返回值表明两个线程在读取期间持有共享锁。共享互斥锁通常用于多个读取者可以同时访问同一资源而不会导致数据竞争,但只有一个写入者能够这样做的情况。
cppreference.com
当您需要读/写锁时,这将非常有用:https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock
std::shared_timed_mutex
。不过,你听说过“读写锁”吗? - WhiZTiM