Question

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 prevent deadlock. Try this and see does deadlock occur.Play with lock order to see if you can achieve deadlock!

#include<stdio.h>

#include<pthread.h>

#include<stdlib.h>

//Function declarations

void *functionA() ;

void *functionB() ;

int var_A, var_B = 0 ; // The shared variables

//Declare mutex

pthread_mutex_t   mutex1 = PTHREAD_MUTEX_INITIALIZER;

pthread_mutex_t   mutex2 = PTHREAD_MUTEX_INITIALIZER;

// MAIN

int main() /*MODIFICATION by "int" type data*/

{

    pthread_t   thread1, thread2 ;

   

    // declare 2 threads

   

    int   rc1, rc2 ;

   

    // Message to the terminal

   

    printf ("\033[2J") ;

   

    // Clear the screen

   

printf ("Deadlock experiment with MUTEX. Does this program lead to deadlock?\n") ;

printf ("=============================================================\n\n") ;

// Create first thread

if ((rc1=pthread_create(&thread1, NULL, &functionA, NULL)))

    {

        printf("Error in creating %d\n",rc1) ;

       

    }

       

        // Create next thread

if ((rc2=pthread_create(&thread2, NULL, &functionB, NULL)))

    {

        printf("Error in creating %d\n",rc2) ;

           

    }

// Remember to use the thread joins

       

pthread_join( thread1, NULL) ;

pthread_join( thread2, NULL) ;

       

pthread_mutex_destroy(&mutex1) ;

pthread_mutex_destroy(&mutex2) ;

       

// main exits

exit(0) ;

   

}

// Thread 1

void *functionA()

{

int   x = 0 ;

// interation counter for the While loop

while (x < 2)

    {

        pthread_mutex_lock(&mutex1) ;

        printf ("I'm T1, just locked mutex1\n") ;

        pthread_mutex_lock(&mutex2) ;

        printf ("I'm T1, just locked mutex2\n") ;

       

        var_A++ ;

        var_B++ ;

       

             

        printf("I am Thread 1: var_A = %d/*/*, var_B = %d*/*/ \n", var_A, var_B) ;

        pthread_mutex_unlock(&mutex2) ;

        printf ("I'm T1, just freed mutex2\n") ;

        pthread_mutex_unlock(&mutex1) ;

        printf ("I'm T1, just freed mutex1\n") ;

        x++ ;

       

    }

pthread_exit (NULL) ; // Thread exits

   

}

// Thread 2

void *functionB() {

int x = 0 ;

// interation counter

while (x < 2)

    {

   

    pthread_mutex_lock(&mutex1) ;

    printf ("I'm T2, just locked mutex1\n") ;

    pthread_mutex_lock(&mutex2) ;

    printf ("I'm T2, just locked mutex2\n") ;

    var_A++ ;var_B++ ;

   printf("I am Thread 2: var_A = %d, var_B = %d \n", var_A, var_B) ;

    pthread_mutex_unlock(&mutex2) ;

    printf ("I'm T2, just freed mutex2\n") ;

    pthread_mutex_unlock(&mutex1) ;

    printf ("I'm T2, just freed mutex1\n") ;

    x++ ;

       

    }

pthread_exit (NULL) ; // Thread exits

   

}

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

The given code does not and cannot go into a deadlock because both threads lock the mutex in the same order, mutex1, followed by mutex2.

In order for a deadlock to be possible, the threads must lock the mutex in different orders. The deadlock occurs when thread1 has locked mutex1 and is waiting for mutex2, while thread2 has locked mutex2 and is waiting for mutex1. Even with the changed order, a deadlock can occur, but is not guaranteed to occur. Increasing the loop count will increase the chances of getting a deadlock.

In the case here, a loop value of 100 caused a deadlock in the 2nd attempt. The modified code is given below followed by the output snapshot when the deadlock occurred.

//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 prevent deadlock. Try this and see does deadlock occur.Play with lock order to see if you can achieve deadlock!

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

//Function declarations
void *functionA() ;
void *functionB() ;

int var_A, var_B = 0 ; // The shared variables

//Declare mutex
pthread_mutex_t   mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t   mutex2 = PTHREAD_MUTEX_INITIALIZER;

// MAIN
int main() /*MODIFICATION by "int" type data*/
{
    pthread_t   thread1, thread2 ;

    // declare 2 threads
    int   rc1, rc2 ;

    // Message to the terminal
    printf ("\033[2J") ;

    // Clear the screen
    printf ("Deadlock experiment with MUTEX. Does this program lead to deadlock?\n") ;
    printf ("=============================================================\n\n") ;
    // Create first thread
    if ((rc1=pthread_create(&thread1, NULL, &functionA, NULL)))
    {
        printf("Error in creating %d\n",rc1) ;
    }

    // Create next thread
    if ((rc2=pthread_create(&thread2, NULL, &functionB, NULL)))
    {
        printf("Error in creating %d\n",rc2) ;
    }
    // Remember to use the thread joins

    pthread_join( thread1, NULL) ;
    pthread_join( thread2, NULL) ;

    pthread_mutex_destroy(&mutex1) ;
    pthread_mutex_destroy(&mutex2) ;

    // main exits
    exit(0) ;
}

// Thread 1
void *functionA()
{
    int   x = 0 ;
    // interation counter for the While loop
    while (x < 100)
    {
        pthread_mutex_lock(&mutex1) ;
        printf ("I'm T1, just locked mutex1\n") ;
        pthread_mutex_lock(&mutex2) ;
        printf ("I'm T1, just locked mutex2\n") ;

        var_A++ ;
        var_B++ ;

        printf("I am Thread 1: var_A = %d/*/*, var_B = %d*/*/ \n", var_A, var_B) ;
        pthread_mutex_unlock(&mutex2) ;
        printf ("I'm T1, just freed mutex2\n") ;
        pthread_mutex_unlock(&mutex1) ;
        printf ("I'm T1, just freed mutex1\n") ;
        x++ ;
    }
    pthread_exit (NULL) ; // Thread exits
}

// Thread 2
void *functionB() {
    int x = 0 ;
    // interation counter
    while (x < 100)
    {
        pthread_mutex_lock(&mutex2) ;
        printf ("I'm T2, just locked mutex2\n") ;
        pthread_mutex_lock(&mutex1) ;
        printf ("I'm T2, just locked mutex1\n") ;
        var_A++ ;var_B++ ;
        printf("I am Thread 2: var_A = %d, var_B = %d \n", var_A, var_B) ;
        pthread_mutex_unlock(&mutex1) ;
        printf ("I'm T2, just freed mutex1\n") ;
        pthread_mutex_unlock(&mutex2) ;
        printf ("I'm T2, just freed mutex2\n") ;
        x++ ;
    }
    pthread_exit (NULL) ; // Thread exits
}

Add a comment
Know the answer?
Add Answer to:
Compile and run the deadlockFree.c program below and report if this program does go into deadlock...
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
  • Read given code RaceOrNot1.c and write all possible outputs of the program. Assume there will be...

    Read given code RaceOrNot1.c and write all possible outputs of the program. Assume there will be no thread creation or joining failures or mutex failures. If you believe there is only one possible output, you just need to write that output. #include <stdio.h> #include <stdlib.h> #include <pthread.h> pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t count_mutex3 = PTHREAD_MUTEX_INITIALIZER; int c[2] = {1,0}; void *UpdateC1(void *arg) {    int i;    for(i=0;i<1000000;i++)    {        pthread_mutex_lock(&count_mutex);        c[0]=(c[0]+1)%2;        c[1]=(c[1]+1)%2;        pthread_mutex_unlock(&count_mutex);    }    return NULL; } void *UpdateC2(void *arg) {    int...

  • 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);   ...

  • In c programming The Consumer Submits processing requests to the producer by supplying a file name, its location and a character. It also outputs the contents of the file provided by the producer...

    In c programming The Consumer Submits processing requests to the producer by supplying a file name, its location and a character. It also outputs the contents of the file provided by the producer to the standard output. The Producer Accepts multiple consumer requests and processes each request by creating the following four threads. The reader thread will read an input file, one line at a time. It will pass each line of input to the character thread through a queue...

  • 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) {   ...

  • Modify the program q1.c by adding calls to uthread_join (and making no other changes) so that...

    Modify the program q1.c by adding calls to uthread_join (and making no other changes) so that it always prints the lines “zero” to “three” in order; i.e., its output must always be the following. q1.c code as below: #include <stdlib.h> #include <stdio.h> #include "uthread.h" uthread_t t0, t1, t2; void randomStall() { int i, r = random() >> 16; while (i++<r); } void* p0(void* v) { randomStall(); printf("zero\n"); return NULL; } void* p1(void* v) { randomStall(); printf("one\n"); return NULL; } void*...

  • 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;...

  • 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...

  • How do I do this C++ in a Unix Environment assignment Given dot1m.c 1. The program (dot1m.c) uses...

    How do I do this C++ in a Unix Environment assignment Given dot1m.c 1. The program (dot1m.c) uses mutex to lock and unlock the shared resource (dotstr.sum) for access control as shown below. pthread_mutex_lock (&mutexsum); dotstr.sum += mysum; printf("Thread %ld did %d to %d: mysum=%f global sum=%f\n", offset,start,end,mysum,dotstr.sum); pthread_mutex_unlock (&mutexsum); 2. Modify dot1m.c program to use reader-writer lock (instead of mutex).      Replace the codes (for mutex) by the codes (for reader-writer lock).            To initialize reader-writer lock, pthread_rwlock_initializer.            At the end,...

  • I am getting the Segmentation fault error on the Ubuntu machine but not on macOS. Any...

    I am getting the Segmentation fault error on the Ubuntu machine but not on macOS. Any help would be appreciated. /**** main.c ****/ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include <pthread.h> #include <string.h> #define WORD_LEN 6 #define TOP 10 char * delim = "\"\'.“”‘’?:;-,—*($%)! \t\n\x0A\r"; struct Word { char word[30]; int freq; }; int threadCount; int fileDescriptor; int fileSize; off_t chunk; struct Word* wordArray; int arrIndex = 0; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;...

  • Read given code RaceOrNot3.c and write all possible outputs of the program. Assume there will be...

    Read given code RaceOrNot3.c and write all possible outputs of the program. Assume there will be no thread creation or joining failures or semaphore failures. If you believe there is only one possible output, you just need to write that output. #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <semaphore.h> #include <errno.h> sem_t s1; int c=0,x=0; void *UpdateC1(void *arg) {    int i;    for(i=0;i<2000000;i++)   {        sem_wait(&s1);        c++;   x++;        sem_post(&s1);    } } void *UpdateC2(void *arg) {    int i,x=0;    for(i=0;i<2999999;i++)   {        sem_wait(&s1);        c++;   x++;       ...

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