42 lines
983 B
C
42 lines
983 B
C
#include <pthread.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
int max;
|
|
// WOW, new word: it means the compiler is not allowed to optimize this varible
|
|
volatile int counter = 0;
|
|
|
|
void* mythread(void* arg) {
|
|
char* letter = arg;
|
|
int i;
|
|
|
|
printf("%s: begin [addr of i: %p]\n", letter, (void*) &i);
|
|
|
|
for (i = 0; i < max; i++) {
|
|
counter = counter + 1;
|
|
}
|
|
|
|
printf("%s: done with counter at %d\n", letter, counter);
|
|
return NULL;
|
|
}
|
|
|
|
int main(int argc, char* argv[]) {
|
|
if (argc != 2) {
|
|
fprintf(stderr, "usage: main-first <loopcount>\n");
|
|
exit(1);
|
|
}
|
|
max = atoi(argv[1]);
|
|
|
|
pthread_t p1, p2;
|
|
printf("main: begin [counter = %d] [%x]\n", counter,
|
|
*(unsigned int*)&counter);
|
|
|
|
pthread_create(&p1, NULL, mythread, "A");
|
|
pthread_create(&p2, NULL, mythread, "B");
|
|
|
|
pthread_join(p1, NULL);
|
|
pthread_join(p2, NULL);
|
|
|
|
printf("main: done\n [counter: %d]\n [should: %d]\n", counter, max * 2);
|
|
return 0;
|
|
}
|