Lab5: add pthread example 1
This commit is contained in:
parent
7a91b4ec51
commit
c163a960bc
1 changed files with 52 additions and 0 deletions
52
lab5/demos/pthread_count_1.c
Normal file
52
lab5/demos/pthread_count_1.c
Normal file
|
@ -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 <pthread.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
Loading…
Reference in a new issue