Search code examples
clinuxmacospthreadsmutex

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.


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.