Skip to content

Instantly share code, notes, and snippets.

@victoryang00
Created November 30, 2021 18:21
Show Gist options
  • Save victoryang00/fcde8eb740130383b7fd3705b7437222 to your computer and use it in GitHub Desktop.
Save victoryang00/fcde8eb740130383b7fd3705b7437222 to your computer and use it in GitHub Desktop.
Memory Ordering
//
// main.cpp
// test_volatile
//
// Created by yiwei yang on 11/30/21.
//
#include <iostream>
#include <stdio.h>
#include <assert.h>
#include <atomic>
using namespace std;
atomic_uint y;
atomic_uint x;
volatile int r2;
volatile int r1 ;
bool assigned_42;
void *writer(void *unused) {
r1 = x.load(memory_order_relaxed);
y.store(r1, memory_order_relaxed);
return NULL;
}
void *reader(void *unused) {
bool assigned_42(false);
r2 = y.load(memory_order_relaxed);
if (r2 != 42) {
assigned_42 = true;
r2 = 42;
}
x.store(r2, memory_order_relaxed);
assert(!assigned_42);
return NULL;
}
int main(int argc, const char * argv[]) {
// insert code here...
for (int i=0;i<1000000;i++){
y=0;
pthread_t writer_thread;
pthread_t reader_thread;
pthread_create(&writer_thread, NULL, writer, NULL);
pthread_create(&reader_thread, NULL, reader, NULL);
pthread_join(reader_thread, NULL);
pthread_join(writer_thread, NULL);}
return 0;
}
@victoryang00
Copy link
Author

line 3 will get into assertion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment