Question: C programing questions using Linux environment Thread2.c #include #include #include #include /* Purpose: Use 2 threads to increment myglobal exactly 40 times in total. Compile:

C programing questions using Linux environment

Thread2.c

#include #include #include #include /* Purpose: Use 2 threads to increment myglobal exactly 40 times in total. Compile: using -pthread option Author: Daniel Robbins */

int myglobal; //C initializes globals to zero

void *thread_function(void *arg) { int i,j; for ( i=0; i<20; i++ ) { j=myglobal; j=j+1; printf("."); fflush(stdout); sleep(0.2); myglobal=j; } return NULL; }

int main(void) {

pthread_t mythread; int i;

if ( pthread_create( &mythread, NULL, thread_function, NULL) ) { printf("error creating thread."); abort(); }

for ( i=0; i<20; i++) { myglobal=myglobal+1; printf("o"); fflush(stdout); sleep(0.21); }

if ( pthread_join ( mythread, NULL ) ) { printf("error joining thread."); abort(); }

printf(" myglobal equals %d ",myglobal);

exit(0);

}

2. Explain why the variable myglobal is usually not 40.

5. Copy thread2.c to threadSem.c, and modify threadSem.c to use an UNNAMED semaphore to synchronize the update of myglobal. You must use the semaphore efficiently, i.e., keep the critical sections as small as possible. You must use functions: sem_wait sem_post sem_init sem_destroy Run threadSem numerous times to verify myglobal is always 40. Given your various runs, what can you say about the interleaving of parent and child threads during run-time?

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!