Skip to content

Instantly share code, notes, and snippets.

@codebje
Last active February 22, 2017 02:37
Show Gist options
  • Save codebje/8c86ccbf1f819f119d88648833613be4 to your computer and use it in GitHub Desktop.
Save codebje/8c86ccbf1f819f119d88648833613be4 to your computer and use it in GitHub Desktop.
Sequential writing of volatile (C) and atomic (C++) and dead-store elimination
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
volatile char toggle = 1;
void *writer(void *unused) {
for (;;) {
toggle = 1;
toggle = 2;
}
return unused;
}
int main() {
pthread_t writer_thread;
pthread_create(&writer_thread, NULL, &writer, NULL);
long ones = 0, twos = 0;
for (int i = 0; i < 100000; i++) {
if (toggle == 1) {
ones++;
} else {
twos++;
}
}
printf("Ones: %ld; twos: %ld\n", ones, twos);
}
#include <iostream>
#include <thread>
#include <atomic>
#include "limits.h"
std::atomic<char> toggle;
void writer() {
for (;;) {
toggle.store(1);
toggle.store(2);
}
}
int main() {
std::thread writer_thread(writer);
toggle.store(1);
long ones = 0, twos = 0;
for (int i = 0; i < INT_MAX; i++) {
if (toggle.load() == 1) {
ones++;
} else {
twos++;
}
}
std::cout << "Ones: " << ones << "; twos: " << twos << "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment