In-class-2
Class: CSCE-313
Notes:
Problem 1
What are the possible outputs of the following program? How can you change the program to make it print "HELPER" before "MAIN"? Note that even when a thread relinquishes CPU with a call to sched_yield(), is there a guaranteed order of execution among the main and helper threads?
#include <pthread.h>
#include <stdio.h>
void *helper(void *arg) {
printf("HELPER");
return NULL;
}
int main() {
pthread_t thread;
pthread_create(&thread, NULL, helper, NULL);
sched_yield();
printf("MAIN");
return 0;
}
Answer:
- It can be:
- MAINHELPER
- HELPERMAIN
- MAIN
- ...
Notes:
- We have no control over how much each will execute before they are context switched
- Lets say HELPER ran and returned, then main thread yielded but will be scheduled again so it prints MAIN
- Lets say MAIN is printed, then it yields to the helper thread so it prints HELPER
- When your main call returns you only printed MAAIN and exit.
- If you return from your main program, your caller will just call
exit()
- If you return from your main program, your caller will just call
Problem 2
What does the following program print?
#include <pthread.h>
#include <stdio.h>
void *helper(void *arg) {
int *num = (int *) arg;
*num = 2;
return NULL;
}
int main() {
int i = 0;
pthread_t thread;
pthread_create(&thread, NULL, helper, &i);
pthread_join(thread, NULL);
printf("i is %d.\n", i);
return 0;
}
Notes:
- You are passing an address of your stack (a pointer to an integer variable in your stack)
- Here you will block until that thread has returned
- Note that the child knows the actual type of the
void *argargument, it is able to cast it to(int *) - Note that
pthreat_joinis not a busy wait, it eventually has to go to the kernel to be blocked
...