我学到了信号灯的概念.我正在努力将其付诸实施. 我已经试着实施了19个多小时,但我做不到,所以我写信寻求你的帮助.
它判断当前两个线程的进度,就像它对CV所做的那样,如果两个线程都输入了输出,它可以恢复后续操作.
以下是代码的全文. `
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <semaphore.h>
#include <pthread.h>
#include <stdlib.h>
void *child1(void *arg) {
printf("child thread 1 entered!\n");
// call semaphoreshere here
printf("child thread 1 exits!\n");
return NULL;
}
void *child2(void *arg) {
printf("child thread 2: entered!\n");
// call semaphores here
printf("child thread 2: exits\n");
return NULL;
}
int main(int argc, char *argv[]) {
pthread_t p1, p2;
printf("parent thread: begin\n");
// init semaphores here
// // sem_init(&empty, 0, 0);
// // sem_init(&full, 0, 0); //Code tried but not working properly
pthread_create(&p1, NULL, child1, NULL);
pthread_create(&p2, NULL, child2, NULL);
pthread_join(p1, NULL);
pthread_join(p2, NULL);
printf("parent thread: end\n");
return 0;
}
` 在代码中仅使用两个信号量,这将try 控制线程的内部执行顺序,以便两个线程都必须输出~~ENTERED消息才能退出.
我想要的执行结果如下.
>>>
parent thread: begin
child thread 1 entered!
child thread 2: entered!
child thread 2: exits
child thread 1 exits!
parent thread: end
>>>
parent thread: begin
child thread 2 entered!
child thread 1: entered!
child thread 1: exits
child thread 2 exits!
parent thread: end
像这样,我只想实现互相监视的角色,看看他们是否已经进入.
如果你能帮忙,我将不胜感激. 谢谢.