Created
May 7, 2019 16:50
-
-
Save starzia/3cfd83f736b54cae1eb856561eb5e576 to your computer and use it in GitHub Desktop.
A buggy parallel swap program
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <pthread.h> | |
static volatile char* person1; | |
static volatile char* person2; | |
static const int LOOPS = 1e4; | |
void* mythread(void* arg) { | |
printf("%s: begin\n", (char*)arg); | |
int i; | |
for (i=0; i<LOOPS; i++) { | |
// swap | |
volatile char* tmp = person1; | |
person1 = person2; | |
person2 = tmp; | |
} | |
printf("%s: done\n", (char*)arg); | |
return NULL; | |
} | |
int main(int argc, char* argv[]) { | |
pthread_t p1, p2; | |
person1 = "Jack"; | |
person2 = "Jill"; | |
printf("main: begin (%s, %s)\n", person1, person2); | |
pthread_create(&p1, NULL, mythread, "A"); | |
pthread_create(&p2, NULL, mythread, "B"); | |
// wait for threads to finish | |
pthread_join(p1, NULL); | |
pthread_join(p2, NULL); | |
printf("main: end (%s, %s)\n", person1, person2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment