Question
Consider the following program that uses the standard Pthreads API: #include #include #include #define NUMBER_OF_THREADS 10 void *print_hello_world(void *tid) { /* This function prints the
Consider the following program that uses the standard Pthreads API:
#include#include #include
#define NUMBER_OF_THREADS 10
void *print_hello_world(void *tid) {
/* This function prints the threads identifier and then exits. */ printf("Hello World. Greetings from thread %d ", tid); pthread_exit(NULL);
}
int main(int argc, char *argv[]) {
/* The main program creates 10 threads and then exits. */ pthread_t threads[NUMBER_OF_THREADS]; int status, i;
for(i=0; i < NUMBER_OF_THREADS; i++) {
printf("Main here. Creating thread %d ", i); status = pthread_create(&threads[i], NULL, print_hello_world,
(void *)i);
if (status != 0) {
printf("Oops. pthread_create returned error code %d ", status)
exit(-1);
}
}
exit(NULL); }
The thread creations and messages printed by the threads are interleaved at random. Is there a way to force the order to be strictly thread 1 created, thread 1 prints message, thread 1 exits, thread 2 created, thread 2 prints message, thread 2 exists, and so on? If so, how? If not, why not?
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started