Skip to content

Instantly share code, notes, and snippets.

@TJesionowski
Created December 13, 2018 23:56
Show Gist options
  • Save TJesionowski/5379f2475e1519cbdb076de1ea5be5ad to your computer and use it in GitHub Desktop.
Save TJesionowski/5379f2475e1519cbdb076de1ea5be5ad to your computer and use it in GitHub Desktop.
A quick and dirty rng with pthreads
// implements a race-based rng using posix threads
#include <pthread.h>
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <unistd.h>
// https://randu.org/tutorials/threads/
volatile uint8_t raced = 0;
void *stamp(void *arg);
pthread_barrier_t index_read;
int main(void) {
pthread_t threads[16];
pthread_barrier_init(&index_read, NULL, 2);
void *(*fptr)(void *);
fptr = &stamp;
for(unsigned int i = 0; i < 16; i++) {
pthread_create(&threads[i], NULL, &stamp, &i);
pthread_barrier_wait(&index_read);
}
while (true) {
printf("raced = %d\n", raced);
sleep(1);
}
}
void *stamp(void *arg) {
unsigned int in = 1 + *(uint8_t *)arg;
pthread_barrier_wait(&index_read);
char bit = in & 1;
char i = (in / 2);
int8_t num = bit << i;
printf("Initialized thread %d setting bit %d to %d\n", in, i, bit);
while (true) {
raced = num^raced;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment