void process(int number, int time) {
printf("Prosess %d kjører\n", number);
sleep(time);
printf(" Prosess %d terminated after %d sekunder\n", number, time);
}
int main(void) {
pid_t pid[7];
int status= 0;
if((pid[1]= fork())== 0) {
process(1, 1);
exit(0);
}
if((pid[3]= fork())== 0) {
process(3, 3);
exit(0);
}
waitpid(pid[1], NULL, 0);
if((pid[5]= fork())== 0) {
process(5, 3);
exit(0);
}
if((pid[2]= fork())== 0) {
process(2, 2);
exit(0);
}
waitpid(pid[3], NULL, 0);
//waitpid(pid[2], NULL, 0);
if((pid[4]= fork())== 0) {
process(4, 2);
exit(0);
}
waitpid(pid[5], NULL, 0);
if((pid[6]= fork())== 0) {
process(6, 3);
exit(0);
}
wait(NULL);
while(wait(&status)> 0) {
//We just wait for the children to finish their processes
}
printf("All processes is now terminated\n");
return 0;
}
我怎样才能把这段代码做同样的事情,而是使用 pthread 和互斥锁?我们被要求创建一个带有 id 的结构方法(应该有 6 个线程,每个线程睡眠不同的时间。),sec(睡眠时间)和 int 信号 [6]。它是一项学校任务,我们没有接受任何 c 培训。请帮忙。