Lab4: add examples

This commit is contained in:
Akemi Izuko 2024-10-08 16:50:03 -06:00
parent 8be540dbbf
commit 7a91b4ec51
Signed by: akemi
GPG key ID: 8DE0764E1809E9FC
2 changed files with 74 additions and 0 deletions

View 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;
}

View 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);
}