I'm using the following code to demonstarte threads and semaphores. it is works well all the way but the program hangs at the point where the threads join. They never join and program hangs there indefinatly. Anybody please, what am I doing wrong??!!
Main Code:
Code:
void* thread_function(void* arg);
sem_t bin_sem;
int main() {
int res;
void* thread_return;
pthread_t a_thread;
res = sem_init(&bin_sem, 0, 0);
if(res != 0) {
printf("Failed to initialize semaphore. Exiting..\n");
exit(EXIT_FAILURE);
}
res = pthread_create(&a_thread, NULL, thread_function, NULL);
if(res != 0) {
printf("Failed to create a thread. Exiting..\n");
exit(EXIT_FAILURE);
}
int i = 5;
for(i = 5; i > 0; i--){
printf("This is parent!!\n");
sem_post(&bin_sem);
sleep(1);
}
printf("Waiting for thread to end..\n");
res = pthread_join(a_thread, &thread_return);
if(res != 0){
printf("Failed to join thread. Exiting . . \n");
exit(EXIT_FAILURE);
}
printf("Thread joined\n");
sem_destroy(&bin_sem);
exit(EXIT_SUCCESS);
}
Thread Code:
Code:
void* thread_function(void* arg) {
sem_wait(&bin_sem);
int i;
for( i=5; i > 0; i--){
printf("This is child!!\n");
sleep(1);
sem_wait(&bin_sem);
}
pthread_exit(NULL);
}