Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
atalay11 opened this issue Jun 25, 2024 · 1 comment
Open

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

atalay11 opened this issue Jun 25, 2024 · 1 comment

Comments

@atalay11
Copy link

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
Copy link
Owner

necatiergin commented Jun 25, 2024 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants