Re: standard atomic read bool exist?
On Feb 19, 10:18 pm, REH <spamj...@stny.rr.com> wrote:
On Feb 19, 3:58 pm, Christopher <cp...@austin.rr.com> wrote:
Does there exist a standard way to atomically read the value of a
bool?
class MultithreadedFoo()
{
bool m_value;
protected:
const bool SafelyReadValue() const
{
// What goes here to prevent the need for locks
// If multiple threads may reach this point?
}
};
class MultithreadedFoo()
{
sig_atomic_t m_value;
protected:
bool SafelyReadValue() const
{
return m_value != 0;
}
};
sig_atomic_t makes no guarantees with regards to threading. In
particular, a signal will execute within the same thread of
execution---and so on the same CPU core; another thread might
not.
Some sort of synchronization is necessary if you want to be sure
that other threads see the modification. At least in theory.
In practice, of course, such flags are useless unless other data
in also involved, and you definitely need synchronization in
order to ensure the correct ordering of the writes and reads.
The simplest solution is to protect all accesses to the bool
with a mutex (pthread_mutex_t, CriticalSection---badly misnamed,
that one, etc.---or boost::mutex and a scoped_lock). *All*
access, not just the write.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34