Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the second function not running and or producing an output? (C in Linux)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>             //needed for Mac Linux

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // Declares Mutex Lock Globally

void* print_i(void *ptr)
{
        pthread_mutex_lock(&mutex); //ensures whole function gets executed without interleaving

        printf("1: I am \n");
        sleep(1);               //program to pause for 1 sec
        printf("in i\n");
        return NULL;            //needed b/c function does not return anything

        pthread_mutex_unlock(&mutex); //releases function to continue rest of program
}

void* print_j(void *ptr)
{
        pthread_mutex_lock(&mutex); //ensures whole function gets executed without interleaving

        printf("2: I am \n");
        sleep(1);               //program to pause for 1 sec
        printf("in j\n");
        return NULL;            //needed b/c function does not return anything

        pthread_mutex_unlock(&mutex); //releases function to continue rest of program
}

int main()
{
        pthread_t t1,t2;
        int rc1 = pthread_create(&t1, NULL, print_i, NULL);
        int rc2 = pthread_create(&t2, NULL, print_j, NULL);
        pthread_join(t1, NULL); //allows functions to iterate completely(T1,T2,Main,T1,T2,Main..)
        pthread_join(t2, NULL); //allows functions to iterate completely(T1,T2,Main,T1,T2,Main..)

        exit(0);
}

We are meant to have a result of:

1: I am/n
in I/n
2: I am/n
in j/n

What my output actually is:

1: I am
in i

After my actual output I then seem to be ‘stuck’ in the program. For example, the up arrow produces ‘^[[A’. Any help would be greatly appreciated to find out why the expected result is not coming. I am using a M1 MacBook Pro.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

After the return statement the next statement does not get the control

    return NULL;            //needed b/c function does not return anything

    pthread_mutex_unlock(&mutex); 

So the mutex is not unlocked.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading