Многопоточность printf () с семафорами в c - PullRequest
0 голосов
/ 13 июня 2018

Я хочу добиться того, чтобы три отдельных отпечатка выполнялись один за другим, печатая сообщение «Какой чудесный мир!».Вместо этого я получаю «что, что, что, что, как чудесно, чудесно, чудесно, мир, мир, мир».Я думаю, что-то не так с pthread_join ().Программа завершится, когда пользователь введет ctrl + c.

#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <semaphore.h>

sem_t Asem;
sem_t Bsem;
sem_t Csem;

void *print_WhatA(){
    while(1){
        sem_wait(&Asem);
        printf("What A ");
        sem_post(&Bsem);
    }
} 

void *print_Wonderful(){
    while(1){
        sem_wait(&Bsem);
        printf("Wonderful ");
        sem_post(&Csem);
    }
}

void *print_World(){
    while(1){
        sem_wait(&Csem);
        printf("World!\n");
        sem_post(&Asem);
    }
}

void main(){
    sem_init(&Asem,0,0);    //initialization of the first semaphore
    sem_init(&Bsem,0,1);    //initialization of the second semaphore
    sem_init(&Csem,0,2);    //initialization of the third semaphore
    pthread_t A_thread;    
    pthread_t B_thread;
    pthread_t C_thread;
    pthread_create(&A_thread,NULL, print_WhatA,NULL);       //thread creation for print_WhatA function 
    pthread_create(&B_thread,NULL, print_Wonderfull,NULL);  //thread creation for print_Wonderful function
    pthread_create(&C_thread,NULL, print_World,NULL);       //thread creation for print_World function
    pthread_join(A_thread,NULL);
    pthread_join(B_thread,NULL);
    pthread_join(C_thread,NULL);
}

1 Ответ

0 голосов
/ 13 июня 2018

Вам следует инициализировать семафоры B и C на 0 и семафор A на 1. Это работает:

#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <semaphore.h>

sem_t Asem;
sem_t Bsem;
sem_t Csem;

void *print_WhatA(){
    while(1){
        sem_wait(&Asem);
        printf("What A ");
        sem_post(&Bsem);
    }
} 

void *print_Wonderful(){
    while(1){
        sem_wait(&Bsem);
        printf("Wonderful ");
        sem_post(&Csem);
    }
}

void *print_World(){
    while(1){
        sem_wait(&Csem);
        printf("World!\n");
        sem_post(&Asem);
    }
}

void main(){
    sem_init(&Asem,0,1);    //initialization of the first semaphore
    sem_init(&Bsem,0,0);    //initialization of the second semaphore
    sem_init(&Csem,0,0);    //initialization of the third semaphore
    pthread_t A_thread;    
    pthread_t B_thread;
    pthread_t C_thread;
    pthread_create(&A_thread,NULL, print_WhatA,NULL);       //thread creation for print_WhatA function 
    pthread_create(&B_thread,NULL, print_Wonderful,NULL);  //thread creation for print_Wonderful function
    pthread_create(&C_thread,NULL, print_World,NULL);       //thread creation for print_World function
    pthread_join(A_thread,NULL);
    pthread_join(B_thread,NULL);
    pthread_join(C_thread,NULL);
}
...