The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

Madhusudhan Srikkanth (7) [Avatar] Offline
#1
Hi Anthony,

In Listing 9.11, you have shown the code for interrupt_flag as below:

class interrupt_flag
{
    std::atomic<bool> flag;
    std::condition_variable* thread_cond;
    std::mutex set_clear_mutex;
public:
    interrupt_flag():thread_cond(0){}
    void set()
    {
        flag.store(true,std::memory_order_relaxed);
        std::lock_guard<std::mutex> lk(set_clear_mutex);
        if(thread_cond)
        {
              thread_cond->notify_all();
        }
    }
    bool is_set() const
    {
        return flag.load(std::memory_order_relaxed);
    }
    /* Other code */
}


Assume that the interruption check is during a normal situation where the thread being interrupted is checking if there are interrupts using your interruption_point() method. So there are no condition variables involved.

So given that the load and store to flag is using memory_order_relaxed, how can the the thread being interrupted see the flag as set without any synchronization? Shouldn't the mutex set_clear_mutex be locked during the load and store to the flag to maintain a happens before relationship?
374822 (6) [Avatar] Offline
#2
The flag is atomic<bool>. The writer and reader can do write(W) and read(R) in two possible sequences. WR or RW. In case of WR the reader will see flag true and do the action. In the case of RW, the writer wrote after a reader's read. In the next read by a reader, the reader will observe true. Even if you put the flag in a lock(), it will not change the behavior. So, in my opinion, this is the correct code. If my understanding is wrong then kindly suggest.