3猴子,每个猴子都会打印它的值。 Monkey1()打印1,依此类推。第一只猴子是最强的,他打印两次1,然后monkey2打印2,然后再次monkey1打印,然后monkey2,然后monkey3可以打印他的价值。3只猴子的打印值必须与信号同步
预期输出: 1 1 2 1 1 2 3 1 1 2 1 1 2 3 1 1 2
等..
我只允许使用2信号量,每只猴子是一个线程。
嗯,我一直在想它一个多小时,我仍然不知道如何实现这一点。我很乐意就如何解决这个问题获得一些指导。
下面的代码的样子,这将帮助是什么系统/语言我使用的,代码不是在诅咒的时刻工作..
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
//3 monkeys so N = 3
#define N 3
sem_t s1,s2;
void* Monkey1(void* param)
{
int i;
for(i = 0; i < 2; i++){
printf("1");
sem_wait(&s1);
}
}
void* Monkey2()
{
int i;
for(i = 0; i < 2; i++){
sem_post(&s1);
}
printf("2");
sem_wait(&s2);
}
void* Monkey3()
{
printf("3");
//sem_wait(&s1);
}
void main()
{
pthread_t thread[N];
int i, ans[N];
sem_init(&s1, 0, 1);
sem_init(&s2,0,0);
for(i=0;i<N;i++)
{
ans[i] = i + 1;
}
if (pthread_create (&thread[0] , NULL , Monkey1 , (void*)&ans[0]) != 0)
{
perror("Could not create thread");
exit(1);
}
if (pthread_create (&thread[1] , NULL , Monkey2 , (void*)&ans[1]) != 0)
{
perror("Could not create thread");
exit(1);
}
if (pthread_create (&thread[2] , NULL , Monkey3 , (void*)&ans[2]) != 0)
{
perror("Could not create thread");
exit(1);
}
for(i=0;i<N;i++)
{
pthread_join(thread[i], NULL);
}
}
它几乎可以工作,它打印211211231121123 ..第2个被删除。你知道如何解决这个问题吗? ? –
另外,我不知道如何去关注它。:( –
猴子2可能会也可能不会启动 - 这取决于线程加入的顺序(它可以通过互斥锁来修复)。重新,它的作用和你的例子完全一样。 – syntagma