我有過程的這個圖。在每個線程中都有新的過程開始第一是流程1,當它結束信號量發佈,下一個可能的過程是2和4
此圖解釋更多:1:http://i49.tinypic.com/34t5uo0.png。我的腳本在一些倍崩潰。過程1,2或4不執行。問題在哪裏?信號燈+並行線程,不能正常工作
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
sem_t semA,semB,semC,semD,semE;
void* process_2 (void* param)
{
sem_wait(&semA);
int pid2, status2;
pid2 = fork();
if (pid2 < 0) {
exit(1);
}
if (pid2==0) {
printf("Process 2\n");
}
else {
wait(&status2);
sem_post(&semC);
}
return NULL;
}
void* process_4(void* param)
{
sem_wait(&semB);
int pid4, status4;
pid4 = fork();
if (pid4 < 0) {
exit(1);
}
if (pid4==0) {
printf("Process 4\n");
exit(0);
}
else {
wait(&status4);
sem_post(&semD);
}
return NULL;
}
void* process_3(void* param)
{
sem_wait(&semC);
int pid3, status3;
pid3 = fork();
if (pid3 < 0) {
exit(0);
}
if (pid3 == 0) {
printf("Process 3\n");
}
else{
wait(&status3);
sem_post(&semE);
}
return NULL;
}
void* process_5(void* param)
{
sem_wait(&semD);
sem_wait(&semE);
int pid5, status5;
pid5 = fork();
if (pid5 < 0) {
exit(0);
}
if (pid5 == 0) {
printf("Process 5\n");
}
else{
wait(&status5);
exit(0);
}
return NULL;
}
int main() {
pthread_t thread_id[4];
pthread_create(&thread_id[0], NULL,&process_2, NULL);
pthread_create(&thread_id[1], NULL,&process_3, NULL);
pthread_create(&thread_id[2], NULL,&process_4, NULL);
pthread_create(&thread_id[3], NULL,&process_5, NULL);
sem_init(&semA,0,0);
sem_init(&semB,0,0);
sem_init(&semC,0,0);
sem_init(&semD,0,0);
sem_init(&semE,0,0);
int pid, status;
pid = fork();
if (pid < 0) {
exit(1);
}
if (pid==0) {
printf("Process 1\n");
}
else {
wait(&status);
sem_post(&semA);
sem_post(&semB);
int i;
for (i = 0; i < 4; i++)
pthread_join(thread_id[i],NULL);
return 0;
}
exit(0);
}
它正在工作,非常感謝! –
這隻記錄你在代碼中遇到的部分問題。我將它們列在單獨的答案中,因爲在評論中列出的時間太長。 –