Re: Efficient way to synchronize bool variables
On Nov 11, 6:52 pm, "Igor Tandetnik" <itandet...@mvps.org> wrote:
Goran wrote:
class CThreadSafeFlag
{
mutable LONG m_Flag;
public:
CThreadSafeFlag(bool bSet=false) : m_Flag(bSet) {}
bool IsSet() const { return InterlockedCompareExchange(&m_Flag, 2,
2) == true; }
void Set() { InterlockedExchange(&m_Flag, 1); }
void Reset() { InterlockedExchange(&m_Flag, 0); }
};
IsSet simply uses "impossible" exchange value to avoid changing
m_Flag, but still return it's value in a thread-safe manner.
InterlockedCompareExchange(&m_Flag, 0, 0) would have worked just as well.=
It says "set the variable to zero only if it's zero already", so it's alwa=
ys a no-op.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not necessar=
ily a good idea. It is hard to be sure where they are going to land, and it=
could be dangerous sitting under them as they fly overhead. -- RFC 1925
Igor,
Actually, I misrepresented the problem here. The Execute() function
are called only by one thread.
OnStart() and OnStop() functions are called by UI thread. I have to
synchronize between these two threads.
In this case which method would you prefer.
If volatile does the synchronization, why we need the InterLockedXXX
functions?
Also, in which cases volatile is useful