2

I am new to boost threading (came from Win32 threading, which has probably ruined me).

So I'm trying to make a more "RAII" way to check that the working loop should still be going. So I made this simple function:

template<typenameT> 
T safe_read(const T& t,boost::mutex& mutex)
{
    boost::interprocess::scoped_lock lock(mutex);
    return t;
}

Is there a boost equivalent to this, since it seems like I'd use this all the time? Also it this an acceptable call?

The idea is to be able to safely do this without using a weirder lock:

while(!safe_read(this->is_killing_,this->is_killing_mutex_))
{
    DoWork();
}
4

2 回答 2

3

boost::atomic<bool>在 boost v1.53.0 中添加,基于 c++11 std::atomics。例如:

#include <boost/atomic.hpp>

boost::atomic<bool> is_killing (false);

while (!is_killing)
{
}

这将消除代码中的显式mutexsafe_access函数,提供所需的同步。

于 2013-05-09T15:35:15.253 回答
0

我认为它不会像你想象的那样工作,因为一旦 safe_access 函数返回,锁就会被释放。

于 2013-05-09T15:08:38.883 回答