I am new to C and trying out conditional critical region. I read up on a couple of sites about Wait() and Signal() but I just can't figure out what my issue is. Hopefully somebody here can point me in the right direction what I am doing wrong here.
I am trying to do make two threads in my sample program here. Thread 1 will assign a value to String stuff and Thread 2 will print the info of the String.
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
void Lock(pthread_mutex_t m);
void Unlock(pthread_mutex_t m);
void Wait(pthread_cond_t t, pthread_mutex_t m);
void Signal(pthread_cond_t);
void Broadcast(pthread_cond_t t);
void* First(void* args);
void* Second(void* args);
char* stuff;
int main(int argc, char** argv){
pthread_t r1, r2;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
if(pthread_create(&r1, NULL, First, NULL))
fprintf(stderr,"Error\n");
if(pthread_create(&r2, NULL, Second, NULL))
fprintf(stderr, "Error\n");
pthread_join(r1, NULL);
pthread_join(r2, NULL);
}
void* First(void* args){
Lock(mutex);
stuff = "Processed";
usleep(500000);
Broadcast(cond);
Unlock(mutex);
pthread_exit(NULL);
return NULL;
}
void* Second(void* args){
Lock(mutex);
Wait(cond, mutex);
usleep(500000);
printf("%s", stuff);
Unlock(mutex);
pthread_exit(NULL);
return NULL;
}
void Lock(pthread_mutex_t m){
pthread_mutex_lock(&m);
}
void Unlock(pthread_mutex_t m){
pthread_mutex_unlock(&m);
}
void Wait(pthread_cond_t t, pthread_mutex_t m){
pthread_cond_wait(&t, &m);
}
void Signal(pthread_cond_t t){
pthread_cond_signal(&t);
}
void Broadcast(pthread_cond_t t){
pthread_cond_broadcast(&t);
}
I face a deadlock when executing this code but I am not sure why. GDB mentions that it stops at Wait() but I am not sure why.