Question

Please explain your answers thoroughly for the following question. 1) Compile thread2.c (remember the -lpthread flag)....

Please explain your answers thoroughly for the following question.

1) Compile thread2.c (remember the -lpthread flag). Run it numerous times, and notice the output usually differs.

a) Why is the variable myglobal usually not 40? Be specific, be precise.

b) In what special case would myglobal be 40? Be specific, be precise.

#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>

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

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

   exit(0);
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Note: Done accordingly. Please comment for any problem. Please Uprate. Thanks

a)

Both threads share a single attribute which is myglobal. Global variable occurs only once per process, and is typically covered by mutex in order to prevent simultaneous access. Now in our case both the threads are modifying the myglobal and then their is context switch after

j = myglobal;

then program will return back to
j = j + 1;

and will use old value and hence we will not get perfecct 40. Take example below : Here due to context switch in between lines of loop threadfunction prints old value(i.e. 7 ) instead of modified value from main(i.e 21).


b)

We will get 40 if context switch is done when whole loop is executed (i.e context switch will be done either before entering the next loop or after completion of loop)

Add a comment
Know the answer?
Add Answer to:
Please explain your answers thoroughly for the following question. 1) Compile thread2.c (remember the -lpthread flag)....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • 1) Compile thread2.c (remember the -lpthread flag). Run it numerous times, and notice the output usually...

    1) Compile thread2.c (remember the -lpthread flag). Run it numerous times, and notice the output usually differs. a) Why is the variable myglobal usually not 40? Be specific, be precise. b) In what special case would myglobal be 40? Be specific, be precise. #include <pthread.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <fcntl.h> /* Purpose: Use 2 threads to increment myglobal exactly 40 times in total. Compile: using -pthread option */ int myglobal = 0; void *thread_function(void *arg) {   ...

  • Please finish the following program /** * Basic POSIX Thread (pthread) Usage 1. * * By...

    Please finish the following program /** * Basic POSIX Thread (pthread) Usage 1. * * By walking through this example you’ll learn: * - How to use pthread_create(). * - How to use pthread_exit(). * - How to use pthread_join(). * */ #include <stdio.h> #include <unistd.h> #include <pthread.h> #include <sys/wait.h> void* ninja(void* arg){ printf("Who’s there?"); fflush(stdout); pthread_exit("ninja"); } // // Expected output: // // Knock knock. // Who's there? - from ninja // Knuc...kles. // int main(int argc, char* argv[]){...

  • i want to fix the solution and provide an explanation why the pthread_join is not working...

    i want to fix the solution and provide an explanation why the pthread_join is not working as intended? #include <stdio.h> /* standard I/O routines */ #include <pthread.h> /* pthread functions and data structures */ void* PrintHello(void* data) { pthread_t tid = (pthread_t)data; /* data received by thread */ pthread_join(tid, NULL); /* wait for thread tid */ printf("Hello from new thread %u - got %u\n", pthread_self(), data); pthread_exit(NULL); /* terminate the thread */ } /* like any C program, program's execution...

  • Compile and run the deadlockFree.c program below and report if this program does go into deadlock...

    Compile and run the deadlockFree.c program below and report if this program does go into deadlock or not. Modify this deadlockFree.c program so that you change the lock/unlock order of the mutexes. Experiment with the order of locks (and maybe extend the number of loop iterations) until you find a scenario where you can demonstrate deadlock. //Program: deadlockFree.c A simple threaded program to demonstrate the deadlock condition.Two threads are used to wait on two MUTEXES. Careful ordering of locks should...

  • a multi-threaded producer / consumer program without any locking or signaling. It therefore has synchronization problems....

    a multi-threaded producer / consumer program without any locking or signaling. It therefore has synchronization problems. Add locks and signals so that it works correctly. /* Homework 5.X */ /* Robin Ehrlich */ /* compile: gcc Homework5.c -lpthread */ #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> struct class {    struct class *next;    int id;    int grade; }; #define SLEEP_TIME 1 #define MAX_PRODUCE 10 static struct class *classHead = NULL; static struct class *classTail = NULL; static...

  • Please change this 2 thread program to a 4 thread program. /*compile as "gcc thread.c -pthread"...

    Please change this 2 thread program to a 4 thread program. /*compile as "gcc thread.c -pthread" */ #include <pthread.h> #include <stdio.h> #include <time.h> #define SIZE 100000000 //100 M //#define SIZE 10000 #define NUMBER_OF_TIMES 100 float a[SIZE]; typedef struct {        int start;        int end;        double sum;        int pid;    } range; void *thread_function(void *arg) //define a function that will be executed from //within a thread {    range *incoming = (range *) arg;...

  • 1. (50 pts) Write a C or C++ program A6p1.c(pp) that accepts one command line argument which is an integer...

    1. (50 pts) Write a C or C++ program A6p1.c(pp) that accepts one command line argument which is an integer n between 2 and 6 inclusive. Generate a string of 60 random upper case English characters and store them somewhere (e.g. in a char array). Use pthread to create n threads to convert the string into a complementary string ('A'<>'Z', 'B'<->'Y', 'C''X', etc). You should divide this conversion task among the n threads as evenly as possible, Print out the...

  • Pleas help I need to create and array to add to my code something like this...

    Pleas help I need to create and array to add to my code something like this for (i = 0; i < NUM_THREADS; ++i) { thr_data[i].tid = i; if ((rc = pthread_create(&thr[i], NULL, thr_func, &thr_data[i]))) { fprintf(stderr, "error: pthread_create, rc: %d\n", rc); return EXIT_FAILURE; ::::::::: CODE ::::::::::::: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h>    int sharedVar = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; /* thread handler */ void *threadHandler(void *vargp) {    int i = 0;    pthread_mutex_lock(&mutex);   ...

  • Solve the Consumer/Producer problem using semaphores. A skeleton program (Save it as producer_consumer.c) is provided to...

    Solve the Consumer/Producer problem using semaphores. A skeleton program (Save it as producer_consumer.c) is provided to you: The main function creates 2 threads: consumer represents the consumer and executes the consume function, and producer represents the producer and executes the  produce function. You should declare and initialize 3 semaphores. Those semaphores should be used in the consume(..) and produce(...) functions. #include <stdio.h> #include <stdlib.h> #include <pthread.h> //compile and link with -pthread #define BUFFER_SIZE 10 int buffer[BUFFER_SIZE]; int in, out; int num;...

  • include<stdio.h> #include<pthread.h> int i=4 ,j=10; void*childfunc(void *p) {    printf("child here.i=%d,j=%d\n",i,j);    i*=3;    j*=3;   ...

    include<stdio.h> #include<pthread.h> int i=4 ,j=10; void*childfunc(void *p) {    printf("child here.i=%d,j=%d\n",i,j);    i*=3;    j*=3;    printf("child here.i=%d,j=%d\n",i,j); } void main() {    pthread_t child1;    pthread_create(&child, Null,childfunc, Null) pthread_join(child,Null);    printf("parent here.i=%d,j=%d\n",i,j);    i*=2;    j*=2;    printf("end of program .i=%d,j=%d\n",i,j); } what is output?

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT