Common::Flag: Add support for TestAndSet + test by implementing basic spinlocks.

This commit is contained in:
Pierre Bourdon
2014-04-14 01:40:20 +02:00
parent 6bdcbad3e4
commit e24cad0780
2 changed files with 50 additions and 1 deletions

View File

@ -3,10 +3,17 @@
// Refer to the license.txt file included.
// Abstraction for a simple flag that can be toggled in a multithreaded way.
// It exposes a very simple API:
//
// Simple API:
// * Set(bool = true): sets the Flag
// * IsSet(): tests if the flag is set
// * Clear(): clears the flag (equivalent to Set(false)).
//
// More advanced features:
// * TestAndSet(bool = true): sets the flag to the given value. If a change was
// needed (the flag did not already have this value)
// the function returns true. Else, false.
// * TestAndClear(): alias for TestAndSet(false).
#pragma once
@ -37,6 +44,17 @@ public:
return m_val.load();
}
bool TestAndSet(bool val = true)
{
bool expected = !val;
return m_val.compare_exchange_strong(expected, val);
}
bool TestAndClear()
{
return TestAndSet(false);
}
private:
// We are not using std::atomic_bool here because MSVC sucks as of VC++
// 2013 and does not implement the std::atomic_bool(bool) constructor.