An Example: Thread Creation
Explore the process of thread creation in operating systems by examining a program that creates and manages multiple threads. Understand how threads run independently, how execution order varies due to the OS scheduler, and why concurrency adds complexity to program behavior.
We'll cover the following...
Let’s get into some of the details. Say you wanted to run a program that creates two threads, each of which does some independent work, in this case, printing “A” or “B”. The code is shown in the code widget below.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "common.h"
#include "common_threads.h"
void *mythread(void *arg) {
printf("%s\n", (char *) arg);
return NULL;
}
int main(int argc, char *argv[]) {
if (argc != 1) {
fprintf(stderr, "usage: main\n");
exit(1);
}
pthread_t p1, p2;
printf("main: begin\n");
Pthread_create(&p1, NULL, mythread, "A");
Pthread_create(&p2, NULL, mythread, "B");
// join waits for the threads to finish
Pthread_join(p1, NULL);
Pthread_join(p2, NULL);
printf("main: end\n");
return 0;
}Explanation
The main program creates two threads, each of which will run the function mythread(), though with different arguments (the string A or B). Once a thread is created, it may start running right away (depending on the whims of the scheduler); alternately, it may be put in a “ready” but not “running” state and thus not run yet. Of course, on a ...