necatiergin / CONCURRENCY

11 stars 1 forks source link

Incorrect Use of Memory Order for std::atomic #1

Open atalay11 opened 2 weeks ago

atalay11 commented 2 weeks ago

The acquire and release memory orders for std::atomic operations are used in the wrong places. They need to be switched to ensure correct synchronization. The code is located at atomic/synchronisation/sync_04.cpp.

Corrected code:

#include <atomic>
#include <syncstream>
#include <iostream>
#include <thread>

std::atomic<int> ready_flag{ false };
int svar = 0;

void consumer()
{
    while (!ready_flag.load(std::memory_order_acquire)) { // It was memory_order_release
        std::osyncstream{ std::cout }.put('.');
    }
    std::osyncstream{ std::cout } << '\n' << svar;
}

void producer()
{
    std::this_thread::sleep_for(std::chrono::milliseconds{ 50 });
    svar = 38764;
    ready_flag.store(true, std::memory_order_release); // It was memory_order_acquire
}

int main()
{
    std::thread th_c{ consumer };
    std::thread th_p{ producer };

    th_c.join();
    th_p.join();
}
necatiergin commented 2 weeks ago

Teşekkürler👍

25 Haz 2024 Sal, saat 14:40 tarihinde Omer Faruk Atalay < @.***> şunu yazdı:

The acquire and release memory orders for std::atomic operations are used in the wrong places. They need to be switched to ensure correct synchronization. The code is located at atomic/synchronisation/sync_04.cpp.

Corrected code:

include

include

include

include

std::atomic ready_flag{ false };int svar = 0; void consumer() { while (!ready_flag.load(std::memory_order_acquire)) { // It was memory_order_release std::osyncstream{ std::cout }.put('.'); } std::osyncstream{ std::cout } << '\n' << svar; }

void producer() { std::this_thread::sleep_for(std::chrono::milliseconds{ 50 }); svar = 38764; ready_flag.store(true, std::memory_order_release); // It was memory_order_acquire } int main() { std::thread th_c{ consumer }; std::thread th_p{ producer };

th_c.join(); th_p.join(); }

— Reply to this email directly, view it on GitHub https://github.com/necatiergin/CONCURRENCY/issues/1, or unsubscribe https://github.com/notifications/unsubscribe-auth/ALC5AJIPMACNJVOTTTKTGW3ZJFJLBAVCNFSM6AAAAABJ3VDN26VHI2DSMVQWIX3LMV43ASLTON2WKOZSGM3TENBWHEYDKNY . You are receiving this because you are subscribed to this thread.Message ID: @.***>