Incorrect Use of Memory Order for std::atomic
atalay11 opened this issue · comments
Omer Faruk Atalay commented
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();
}
Necati Ergin commented
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 <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();
}
—
Reply to this email directly, view it on GitHub
<#1>, or unsubscribe
<https://github.com/notifications/unsubscribe-auth/ALC5AJIPMACNJVOTTTKTGW3ZJFJLBAVCNFSM6AAAAABJ3VDN26VHI2DSMVQWIX3LMV43ASLTON2WKOZSGM3TENBWHEYDKNY>
.
You are receiving this because you are subscribed to this thread.Message
ID: ***@***.***>