gpt4 book ai didi

c++ - 使 C++ 类成为监视器(在并发意义上)

转载 作者:IT老高 更新时间:2023-10-28 22:35:59 26 4
gpt4 key购买 nike

我想确保一次只有一个线程可以运行我的 C++ 类的方法。换句话说,让类表现得像 Monitor .

有没有一种模式、模板化的方式来做到这一点,或者我可以使用一些 Boost 类?因为到目前为止我唯一的想法是添加一个关键部分成员,并在每个方法的开头获取它并在最后释放它(当然使用 RAII)。但这似乎很多余,我不能将它重用于其他类。

最佳答案

您可以通过明智地使用 operator-> 和现代 c++ 来实现这一点,这提供了比以前接受的答案更简洁的语法:

template<class T>
class monitor
{
public:
template<typename ...Args>
monitor(Args&&... args) : m_cl(std::forward<Args>(args)...){}

struct monitor_helper
{
monitor_helper(monitor* mon) : m_mon(mon), m_ul(mon->m_lock) {}
T* operator->() { return &m_mon->m_cl;}
monitor* m_mon;
std::unique_lock<std::mutex> m_ul;
};

monitor_helper operator->() { return monitor_helper(this); }
monitor_helper ManuallyLock() { return monitor_helper(this); }
T& GetThreadUnsafeAccess() { return m_cl; }

private:
T m_cl;
std::mutex m_lock;
};

这个想法是您使用箭头运算符来访问底层对象,但这会返回一个辅助对象,该对象会锁定然后解锁函数调用周围的互斥锁。然后通过重复应用 operator-> 的语言的魔力,您可以获得对底层对象的引用。

用法:

monitor<std::vector<int>> threadSafeVector {5};

threadSafeVector->push_back(0);
threadSafeVector->push_back(1);
threadSafeVector->push_back(2);

// Create a bunch of threads that hammer the vector
std::vector<std::thread> threads;
for(int i=0; i<16; ++i)
{
threads.push_back(std::thread([&]()
{
for(int i=0; i<1024; ++i)
{
threadSafeVector->push_back(i);
}
}));
}

// You can explicitely take a lock then call multiple functions
// without the overhead of a relock each time. The 'lock handle'
// destructor will unlock the lock correctly. This is necessary
// if you want a chain of logically connected operations
{
auto lockedHandle = threadSafeVector.ManuallyLock();
if(!lockedHandle->empty())
{
lockedHandle->pop_back();
lockedHandle->push_back(-3);
}
}

for(auto& t : threads)
{
t.join();
}

// And finally access the underlying object in a raw fashion without a lock
// Use with Caution!

std::vector<int>& rawVector = threadSafeVector.GetThreadUnsafeAccess();
rawVector.push_back(555);

// Should be 16393 (5+3+16*1024+1)
std::cout << threadSafeVector->size() << std::endl;

关于c++ - 使 C++ 类成为监视器(在并发意义上),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12647217/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com