diff --git a/lab5/demos/pthread_count_1.c b/lab5/demos/pthread_count_1.c new file mode 100644 index 0000000..d5b07d6 --- /dev/null +++ b/lab5/demos/pthread_count_1.c @@ -0,0 +1,52 @@ +/* + * This program ends up in a threadrace when the argument is around 1M + * + * We need synchronization primitives to help here! + */ +#include +#include +#include + +struct args { + int max; + char letter; +}; + +volatile int counter = 0; + +void* count_thread(void* arg) { + struct args* a = arg; + + for (int i = 0; i < a->max; i++) { + counter = counter + 1; + } + + printf("Thread %c: done with counter at %d\n", a->letter, counter); + return NULL; +} + +void* make_args(int max, char letter) { + struct args* a = malloc(sizeof(struct args)); + a->max = max; + a->letter = letter; + + return (void*) a; +} + +int main(int argc, char* argv[]) { + if (argc != 2) { + exit(1); + } + + int max = atoi(argv[1]); + + pthread_t p1, p2; + pthread_create(&p1, NULL, count_thread, make_args(max, 'A')); + pthread_create(&p2, NULL, count_thread, make_args(max, 'B')); + + pthread_join(p1, NULL); + pthread_join(p2, NULL); + + printf("main: done\n [counter: %d]\n [should: %d]\n", counter, max * 2); + return 0; +}