Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Consider the following code using the POSIX Pthreads API:

#include #include #include #include

int myglobal = 0;

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) != 0)

{

printf("error creating thread.");

abort(); }

for(i = 0; i < 20; i++)

{

3

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); }

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() re- turns zero on success and a nonzero error code on failure. The third argument of pthread_create() is the name of a function that the new thread will ex- ecute when it starts. When this thread_function() returns, the thread terminates. Meanwhile the main program itself denes a thread, so there are two threads executing. The pthread_join() function causes the main thread to wait until the new thread completes.

Questions

  1. What does this program accomplish? Please describe what happens with the global value myglobal. What does the thread_function() do and when does it run? What is the main() funciton doing? What is sleep() and what purpose does it serve?

  1. Here is output from the above program being executed
  2. $ ./thread2
  3. ..o.o.o.o.oo.o.o.o.o.o.o.o.o.o..o.o.o.oo
  4. myglobal equals 21

Is this the output you would expect? If not, what has gone wrong and how would you fix it (please show code)?

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Big Data With Hadoop MapReduce A Classroom Approach

Authors: Rathinaraja Jeyaraj ,Ganeshkumar Pugalendhi ,Anand Paul

1st Edition

1774634848, 978-1774634844

More Books

Students also viewed these Databases questions

Question

In what form does rivalry occur in an oligopoly?

Answered: 1 week ago

Question

Identify job situations that often present ethical dilemmas.

Answered: 1 week ago