diff --git a/lab4/demos/parallel_count.c b/lab4/demos/parallel_count.c new file mode 100644 index 0000000..1ddda0a --- /dev/null +++ b/lab4/demos/parallel_count.c @@ -0,0 +1,42 @@ +#include +#include +#include + +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 \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; +} diff --git a/lab4/demos/pthread_exit_status.c b/lab4/demos/pthread_exit_status.c new file mode 100644 index 0000000..b38dad6 --- /dev/null +++ b/lab4/demos/pthread_exit_status.c @@ -0,0 +1,32 @@ +#include +#include +#include + +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); +}