Lab4: add examples
This commit is contained in:
parent
8be540dbbf
commit
7a91b4ec51
2 changed files with 74 additions and 0 deletions
42
lab4/demos/parallel_count.c
Normal file
42
lab4/demos/parallel_count.c
Normal file
|
@ -0,0 +1,42 @@
|
||||||
|
#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;
|
||||||
|
}
|
32
lab4/demos/pthread_exit_status.c
Normal file
32
lab4/demos/pthread_exit_status.c
Normal file
|
@ -0,0 +1,32 @@
|
||||||
|
#include <pthread.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
void* integer_return(void* arg) {
|
||||||
|
return (void*) 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
void* string_return(void* arg) {
|
||||||
|
char* string = calloc(4, sizeof(char));
|
||||||
|
|
||||||
|
string[0] = 'c';
|
||||||
|
string[1] = 'a';
|
||||||
|
string[2] = 't';
|
||||||
|
|
||||||
|
pthread_exit((void*) string);
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(void) {
|
||||||
|
pthread_t thread_id_1;
|
||||||
|
pthread_t thread_id_2;
|
||||||
|
|
||||||
|
pthread_create(&thread_id_1, NULL, integer_return, NULL);
|
||||||
|
pthread_create(&thread_id_2, NULL, string_return, NULL);
|
||||||
|
|
||||||
|
void* thread_return_value;
|
||||||
|
pthread_join(thread_id_1, &thread_return_value);
|
||||||
|
printf("The first thread returned: %d\n", *(int*) thread_return_value);
|
||||||
|
|
||||||
|
pthread_join(thread_id_2, &thread_return_value);
|
||||||
|
printf("The second thread returned: %s\n", (char*) thread_return_value);
|
||||||
|
}
|
Loading…
Reference in a new issue