Question: #include #include #include #include int myglobal; void *thread_function(void *arg) { int i,j; for ( i=0; i <20; i++ ) { j=myglobal; j=j+1; printf(.); fflush(stdout); sleep(1);

#include #include #include #include

int myglobal;

void *thread_function(void *arg) { int i,j;

for ( i=0; i<20; i++ ) { j=myglobal; j=j+1; printf(.); fflush(stdout); sleep(1); myglobal=j; }

return NULL;

}

int main(void) {

pthread_t mythread; int i;

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

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

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

printf( myglobal equals %d ,myglobal); exit(0); }

My question

When the function pthread_create() is called does the code split into 2 threads? So is the code running in main and in the thread_function "simultaneously"?

Output is o..oo..oo.o.o..oo.o..oo..oo.o.o.o.o.o.o.

If the code is running "simultaneously" in main and the thread_function(), is the output varied (o..oo..oo.o.o) because of the the sleep function in other words why isn't the output o.o.o.o.o.o.o?

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!