Domanda

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();
}
È stato utile?

Soluzione

boost::atomic<bool> was added in boost v1.53.0, based on c++11 std::atomics. For example:

#include <boost/atomic.hpp>

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

while (!is_killing)
{
}

This would eliminate the explicit mutex and the safe_access function from the code, providing the synchronization required.

Altri suggerimenti

I don't think it works the way you think it does, because once the safe_access function returns, the lock is released.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top