I'm learning multi-threading and trying to create a program that can print two strings alternately. I have written the following code :
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_mutex_t lock;
void print(char a[50]){
pthread_mutex_lock(&lock);
printf("%s", a); //output console is the shared resource
sleep(2);
pthread_mutex_unlock(&lock);
}
void* hello(void* status){
while(*((char*)status) != '\n'){
print("Hello World\n");
}
}
void* bye(void* status){
while(*((char*)status) != '\n'){
print("Goodbye World\n");
}
}
int main(){
pthread_t id1, id2;
char status = '\0';
int state;
if (pthread_mutex_init(&lock, NULL) != 0) {
printf("\n mutex init has failed\n");
exit(1);
}
printf("Starting Threads (Press Enter to terminate)\n");
state = pthread_create(&id1, NULL, hello, &status);
if(state != 0){
printf("Could not create thread, exiting.\n");
exit(1);
}
state = pthread_create(&id2, NULL, bye, &status);
if(state != 0){
printf("Could not create thread, exiting.\n");
exit(1);
}
scanf("%c", &status);
printf("Out of The Threads\n");
pthread_mutex_destroy(&lock);
return 0;
}
According to what I understand, the mutex should lock the print function once for the hello function and then for the bye function. But I only get this output:
Starting Threads (Press Enter to terminate)
Hello World
Hello World
Hello World
Hello World
Hello World
Why does only the hello function get allocated the print function? How do I get it do print both?