Skip to content

Instantly share code, notes, and snippets.

@pftbest
Created November 10, 2017 09:29
Show Gist options
  • Save pftbest/0900175b8f9319d5b8c8a57565a649f2 to your computer and use it in GitHub Desktop.
Save pftbest/0900175b8f9319d5b8c8a57565a649f2 to your computer and use it in GitHub Desktop.
// complie with:
// clang++ -O3 -std=c++11 -pthread -fsanitize=thread main.cpp
#include <atomic>
#include <thread>
#include <iostream>
static uint8_t data;
static std::atomic<bool> flag = {false};
static int produce(uint8_t d) {
if (flag.load(std::memory_order_relaxed)) { // memory_order_consume ??
return -1;
}
data = d;
flag.store(true, std::memory_order_release);
return 0;
}
static int consume() {
if (!flag.load(std::memory_order_acquire)) {
return -1;
}
uint8_t d = data;
flag.store(false, std::memory_order_release);
return d;
}
int sum1 = 0;
int sum2 = 0;
void foo() {
for (int i = 0; i < 1000; i++) {
int v = (uint8_t)i;
while (produce(v) < 0) {}
sum1 += v;
}
}
void bar() {
for (int i = 0; i < 1000; i++) {
int v;
while (v = consume(), v < 0) {}
sum2 += v;
}
}
int main() {
std::thread t1(foo);
std::thread t2(bar);
t2.join();
t1.join();
std::cout << "t1: " << sum1 << "\n";
std::cout << "t2: " << sum2 << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment