preshing / cpp11-on-multicore

Various synchronization primitives for multithreaded applications in C++11.
zlib License
517 stars 102 forks source link

AutoResetEvent::Signal #10

Closed jurgen-kluft closed 6 years ago

jurgen-kluft commented 6 years ago

Hello, i have a question related to the signal function of AutoResetEvent where the load statement of m_status is not executed again after a fail of compare_exchange_weak.

void signal()  
{
    /// --> this below load statement of m_status should be in the for loop
    int oldStatus = m_status.load(std::memory_order_relaxed);
    for (;;)    // Increment m_status atomically via CAS loop.
    {
        assert(oldStatus <= 1);
        int newStatus = oldStatus < 1 ? oldStatus + 1 : 1;
        if (m_status.compare_exchange_weak(oldStatus, newStatus, std::memory_order_release, std::memory_order_relaxed))
            break;
        // The compare-exchange failed, likely because another thread changed m_status.
        // oldStatus has been updated. Retry the CAS loop.
        // --> We can retry the CAS loop but we still have an old 'oldStatus' so the next CAS
        // --> will surely fail again.
    }
    if (oldStatus < 0)
        m_sema.signal();    // Release one waiting thread.
}
preshing commented 6 years ago

If compare_exchange_weak fails, it automatically loads the latest value of m_status into oldStatus, which is passed by reference.

See here: "Otherwise, loads the actual value stored in *this into expected (performs load operation)."

jurgen-kluft commented 6 years ago

Thanks Jeff, learned something today :-)

On 14 November 2017 at 21:06, Jeff Preshing notifications@github.com wrote:

Closed #10 https://github.com/preshing/cpp11-on-multicore/issues/10.

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/preshing/cpp11-on-multicore/issues/10#event-1340811171, or mute the thread https://github.com/notifications/unsubscribe-auth/AHMMjRLjK5FASBmkzwUIpW0yKusKtnhvks5s2ZA8gaJpZM4QdDVn .