0

I using pthread_cond_wait() and pthread_cond_signal() function to create a multithreaded program. It working correctly if condition correct, but condition incorrect, it not working, it not ignore function printinput(), it stay here, not run continue. Can you help me checking this error?

My code:

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

pthread_mutex_t mutex;
pthread_cond_t cond;

//Read input value
void* readinput(void *arg)
{
    pthread_mutex_lock(&mutex);
        int a;
        printf("Input:");
        scanf("%d",&a);
        printf("Value: %d\n",a);
        /*
        if condition correct then "printinput" function
        else ignore that function
        */
        if (a>=2 && a<=8)
        {
            pthread_cond_signal(&cond);
        }
    pthread_mutex_unlock(&mutex);
    pthread_exit((void *)a);
}

//print input value if condition correctly
void* printinput(void *arg)
{
    pthread_mutex_lock(&mutex);
    //Block and wait for cond Singal
        pthread_cond_wait(&cond,&mutex);
        printf("Your value between 2 and 8 \n\n");
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
}
int main()
{
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);
    pthread_t th1;
    pthread_t th2;
    while (1)
    {

        //Create pthread
        pthread_create(&th1,NULL,&printinput,NULL);
        pthread_create(&th2,NULL,&readinput,NULL);

        //Wait pthread done
        pthread_join(th1,NULL);
        pthread_join(th2,NULL);
        Sleep(1000);
    }
}

Result:

Input:5 
Value: 5 
Your value between 2 and 8 
Input:10 Value: 10
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

0

pthread_cond_wait() suspends the current thread until the relevant condition is signalled.

For input 5 the first thread signals the condition as it's part of if (a >= 2 && a <= 8) block.

For input 10 the above block is skipped so the condition is never signalled. Therefore the second thread is never woken up and is stuck forever.

Additionally, note there is race condition and I'm actually surprised that the program is often working. In case the first thread locks the mutex, the second thread doesn't enter the mutex section until the first thread function is finished, therefore the condition is signalled before the wait on that condition is invoked. In such situation the second thread would be stuck forever as well.

For the solution working in the way you expect (i.e. consuming true/false from the first thread in the second thread), I'd suggest implementing a queue into which the first thread sends the outputs and the second thread consumes it. It'll fix the race condition too. For the implementation see for example https://stackoverflow.com/a/4577987/4787126

Community
  • 1
  • 1
Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43