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:

Notes:

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:

...