atomic_flag is a really low level construct that should not be widely used. However, I believe that you are using the work as you plan, with the possible exception of the possibility of removing the flag in exceptional cases. If an exception other than that corresponding to std::exception occurs, the flag is not cleared.
Normally RAII should be used for this kind of thing. "R" usually means "resource", but I like Jon Kalb's use of "responsibility." After setting the flag, you must clear the flag when it is done, so you should use RAII to ensure that the responsibility is fulfilled. If all you need to do in exceptional cases can be done this way, then the try / catch pair will disappear.
if ( !std::atomic_flag_test_and_set( &::_my_flag ) ) { flag_clearer x(&::_my_flag); // do my stuff here }
But you do not need to write the flag_clearer type yourself. Instead, you can simply use higher-level constructs such as mutexes and lock_guard:
namespace { std::mutex my_flag; } myclass::do_something() { if ( my_flag.try_lock() ) { std::lock_guard<std::mutex> x(my_flag, std::adopt_lock);
source share