简体   繁体   中英

Thread-safe and unique execution of nested function

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";
        }
};

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;
};

Online Demo

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.

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);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM