I have a simple boolean value I need to test and set in a thread-safe manner. If one thread is already working, I want the second thread to exit. If I understand std::atomic_flag
correctly, this should work fine. However, I'm not confident I understand std::atomic_flag
correctly :) I can't seem to find many simple examples online, save for this spinlock example:
// myclass.cpp
#using <atomic>
namespace // anonymous namespace
{
std::atomic_flag _my_flag = ATOMIC_FLAG_INIT;
} // ns
myclass::do_something()
{
if ( !::_my_flag.test_and_set() ) )
{
// do my stuff here; handle errors and clear flag when done
try
{
// do my stuff here
}
catch ( ... )
{
// handle exception
}
::_my_flag.clear(); // clear my flag, we're done doing stuff
}
// else, we're already doing something in another thread, let's exit
} // do_something
Update: updated code based on suggestions below, forming a decent template for proper use of std::atomic_flag
. Thanks all!