好吧,代码弄短了,范围缩小了,请大家再帮忙看看
semaphore mutex={1,NULL};
semaphore f1turn={1,NULL};
semaphore f2turn={0,NULL};
void f1(void)
{
while(i1<10)
{
p(&f1turn);
p(&mutex);
printf("a thread f1 done now i1=%d \n",i1);
i1++;
v(&mutex);
v(&f2turn);
}
}
void f2(void)
{
while(i2<10)
{
p(&f2turn);
p(&mutex);
printf("b thread f2 done now i2=%d \n",i2);
i2++;
v(&mutex);
v(&f1turn);
}
}
void main(void)
{
i1=0;
i2=0;
{
create("f1",(codeptr)f1,1024);
create("f2",(codeptr)f2,1024);
clrscr();
f1();
f2();
printf("\n\n\n\n\n\nholy shit!!!!!!!'b' always once more than 'a'!!!!
fuck!!! \n\n\n\n\n\n");
system("pause");
}
clrscr();
用信号量实现两个线程的互斥。
已经把数据结构的那部分省略了。现在的问题就是f2里面的while(i2<10),在f1,f2互斥执行到第20次之后,f2在i2=11的情况下还能再执行一次,导致‘b’在最后多输出了一次。我无解,请大家帮忙看看!