Reputation: 59
I have a class MyClass
whose function A
is executed many times in parallel. Then, there is function B
that should only be executed once. My initial setup looks simple but I doubt that it is thread-safe. How can I make it thread-safe? I'm using C++11.
class MyClass {
public:
void A() {
static bool execute_B = true;
if (execute_B) {
execute_B = false;
B();
}
}
private:
void B() {
std::cout << "only execute this once\n";
}
};
Upvotes: 1
Views: 298
Reputation: 8785
Yes, your code is not thead-safe: several threads can enter inside the body of if
statement before execute_B
will be set to false. Also, execute_B
is not atomic, so you can have problems with visibility of changes between threads.
There are many ways you can make it thread-safe. Note that version (1), (2) and (4) will block other thread from executing A
past the point of B
execution, until B
execution is finished.
1) Already mentioned std::call_once
:
void A() {
static std::once_flag execute_B;
std::call_once(flag1, [this](){ B(); });
}
2) Calling B
as result of initializating static variable:
void A() {
static bool dummy = [this](){ B(); return true; });
}
3) Using atomic exchange:
void A() {
static std::atomic<bool> execute_B = true;
if(execute_B.exchange(false, std::memory_order_acq_rel))
B();
}
4) Protecting check with a mutex (to avoid perfomance degradation later, use double-checked locking):
void A() {
static std::mutex m_;
static std::atomic<bool> execute_B = true;
if(execute_B.load(std::memory_order_acquire)) {
std::unique_lock<std::mutex> lk(m_);
if(execute_B.load(std::memory_order_relaxed)) {
B();
execute_B.store(false, std::memory_order_release);
}
}
}
Upvotes: 2
Reputation: 62975
This is a primary use-case for std::atomic_flag
:
class MyClass {
public:
void A() {
if (!execute_B_.test_and_set()) {
B();
}
}
private:
void B() {
std::cout << "only execute this once\n";
}
std::atomic_flag execute_B_ = ATOMIC_FLAG_INIT;
};
Note that any solutions involving static
will allow only one invocation of MyClass::B
, even across multiple MyClass
instances, which may or may not make sense for you; assuming it doesn't make sense, this approach instead allows one invocation of MyClass::B
per MyClass
instance.
Upvotes: 3