'C program to print a sentence using threads & semaphores with infinite loop
i am currently trying to make a programm which will print the sentece "What a wonderful world" using three threads. The first thread should print "What A" , the second "Wonderful", and the third "World" forever. All these should be synchronized with sempahores. I have trying doing that, but after 3-4 whole runs of the infinitive loop, the sentence changes and becomes "Wonderful What a world" etc. Any help? Thank you for your time!
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <semaphore.h>
#include <string.h>
sem_t mutex;
void *thread_function(void *arg)
{
char *k=arg;
sem_wait(&mutex);
while(1){
printf("%s ", k);
fflush(stdout);
sleep(1);
sem_post(&mutex);
}
pthread_exit(NULL);
}
int main()
{
sem_init(&mutex, 0, 1);
char k[3][11]={"What A", "Wonderful" ,"World"};
pthread_t mythread1,mythread2,mythread3;
pthread_create( &mythread1, NULL, thread_function, k[2]);
pthread_create( &mythread2, NULL, thread_function, k[1]);
pthread_create( &mythread3, NULL, thread_function, k[0]);
pthread_join ( mythread3, NULL);
pthread_join ( mythread2, NULL);
pthread_join ( mythread1, NULL);
pthread_exit(NULL);
sem_destroy(&mutex);
return 0;
}
Solution 1:[1]
There are a couple of issues. You cannot achieve this with one semaphore as you cannot enforce the order. You need 3 semaphores (ideally in an array) and pass the index for each thread (make this the same index as the word to be printed). Make the semaphore array and the word array global to keep this simple.
Ensure that the first semaphore is initialized to 1, and the rest initialized to 0.
In the thread, wait for the semaphore (based on the index passed), print the word and then post to the next semaphore (mutex[(index+1) % 3]
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Catch22 |