Yel*_*low 3 c++ multithreading mutex
我有一个对象列表Dinosaur,可以添加、删除这些对象,并且恐龙本身需要喂食。这一切都发生在高度多线程的环境中,因此列表受到互斥保护。
static Mutex s_dinosaurMutex;
static vector<Dinosaur> s_dinosaurList;
void AddDinosaur(const Dinosaur& dinosaur)
{
s_dinosaurMutex.Lock();
s_dinosaurList.push_back(dinosaur);
s_dinosaurMutex.Unlock();
}
void RemoveDinosaur(const Dinosaur& dinosaur)
{
s_dinosaurMutex.Lock();
vector<IMadderReceiver*>::iterator it = find(s_dinosaurList.begin(), s_dinosaurList.end(), dinosaur);
if (it != s_dinosaurList.end())
s_dinosaurList.erase(it);
s_dinosaurMutex.Unlock();
}
void FeedDinosaur(const Dinosaur& dinosaur)
{
s_dinosaurMutex.Lock();
vector<IMadderReceiver*>::iterator it = find(s_dinosaurList.begin(), s_dinosaurList.end(), dinosaur);
if (it != s_dinosaurList.end())
(*it).Feed(); // Feeding a dinosaur can take a long time, ~ 1 second
s_dinosaurMutex.Unlock();
}
Run Code Online (Sandbox Code Playgroud)
现在问题出在喂养上。这可能需要很长时间,但如果多个线程同时喂养相同(或不同)的恐龙,那绝对没问题。因此,馈送过程不应停止其他FeedDinosaur调用,但应停止添加和删除调用,并等待这些调用完成。目前的行为是,许多线程正在排队以喂养恐龙,这使得系统陷入停滞。
是否有一种特定的(类似互斥体)设计模式允许需要只读访问的 ok-ing 线程的这种行为?
这是一个读写器互斥锁;Boost 和 C++ 使用更通用的术语“共享互斥体”,因为它可用于除多个读取器-单个写入器之外的模式。
Boost.Threadshared_mutex从 1.35.0 版本开始(C++ 中的读/写锁)。C++shared_timed_mutex从 C++14 开始就有,并且shared_mutex在 C++17 中也会有;在此之前,您可以使用 C++14 shared_timed_mutex,但不使用超时机制。
在您的编写器线程中,锁定共享互斥体以进行唯一访问(使用 a unique_lock);在您的读取器线程中,锁定共享互斥体以进行共享访问(使用 a shared_lock)。
| 归档时间: |
|
| 查看次数: |
1104 次 |
| 最近记录: |