/******************************************************************************
Online C Compiler.
Code, Compile, Run and Debug C program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t lock;
pthread_cond_t cv;
int count = 0;
int runs = 100;
int deadlocks = 0;
void *
routine ()
{
pthread_mutex_lock (&lock);
if (count < 5)
{
pthread_cond_wait (&cv, &lock);
printf ("routine: got signal (%d)\n", count);
}
else
{
printf ("routine: signal already sent\n");
deadlocks++;
}
pthread_mutex_unlock (&lock);
}
void *
routine2 ()
{
pthread_mutex_lock (&lock);
for (int i = 0; i < 7; i++)
{
count++;
if (count == 5)
pthread_cond_signal (&cv);
}
pthread_mutex_unlock (&lock);
}
int
main ()
{
pthread_mutex_init (&lock, NULL);
pthread_cond_init (&cv, NULL);
pthread_t t1, t2;
for (int idx = 0; idx < runs; idx++)
{
count = 0;
pthread_create (&t1, NULL, &routine, NULL);
pthread_create (&t2, NULL, &routine2, NULL);
pthread_join (t1, NULL);
pthread_join (t2, NULL);
}
pthread_mutex_destroy (&lock);
pthread_cond_destroy (&cv);
printf ("Number of potential deadlocks encountered from %d runs: %d\n",
runs, deadlocks);
}