Question: Consider the following code using the POSIX Pthreads API: thread2.c #include #include #include #include int myglobal; void *thread_function(void *arg) { int i,j; for ( i=0;

Consider the following code using the POSIX Pthreads API:

thread2.c

#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(“\nmyglobal equals %d\n”,myglobal);

exit(0);

}

In main() we first declare a variable called mythread, which has a type of pthread_t. This is essentially an ID for a thread. Next, the if statement creates a thread associated with mythread. The call pthread_create() returns zero on success and a nonzero value on failure. The third argument of pthread_create() is the name of a function that the new thread will execute when it starts. When this thread_function() returns, the thread terminates. Meanwhile, the main program itself defines a thread, so that there are two threads executing. The pthread_join function enables the main thread to wait until the new thread completes.

a. What does this program accomplish?

b. Here is the output from the executed program:

$ ./thread2

..o.o.o.o.oo.o.o.o.o.o.o.o.o.o..o.o.o.o.o

myglobal equals 21

Is this the output you would expect? If not, what has gone wrong?


Step by Step Solution

3.30 Rating (162 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

a This program creates a new thread Both the main thread and the new thread then ... View full answer

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

Document Format (1 attachment)

Word file Icon

451-C-S-D-B-O-S (55).docx

120 KBs Word File

Students Have Also Explored These Related Operating System Questions!