В настоящее время я пытаюсь создать программу, которая будет печатать фразу «Какой чудесный мир» с использованием трех потоков. Первый поток должен печатать «What A», второй «Wonderful», а третий «World» навсегда. Все это должно быть синхронизировано с семпахорами. Я пытался это сделать, но после целых 3-4 прогонов инфинитива l oop предложение меняется и становится «Wonderful What a world» et c. Любая помощь? Спасибо за уделенное время!
#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;
}