嗨 当我运行下面的代码时,我发现信号线程在另一个线程开始之前会继续运行很长时间......为什么会这样呢?是不是被唤醒的线程应该在信号发布者释放锁后立即运行?或者OS需要很长时间才能将睡眠线程放回就绪队列?cond.signal或lock.release有问题吗?
#include pthread.h
#include stdio.h
#include stdlib.h
void stupidfunction1(void *arg);
void stupidfunction2(void *arg);
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
int thread1count,thread2count;
int thread1waiting = 0;
int thread2waiting = 0;
void main()
{
printf("Hello World\n");
pthread_t thread1,thread2;
int i;
thread1count = 0;
thread2count = 0;
i = pthread_create(&thread1,NULL,&stupidfunction1,NULL);
i = pthread_create(&thread2,NULL,&stupidfunction2,NULL);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
printf("Done with everythinh");
}
void stupidfunction1(void *arg)
{
int i = 0;
for(i = 0;i<50;i++)
{
thread1count++;
pthread_mutex_lock(&mutex1);
if((thread1count-thread2count)>5)
{
thread1waiting = 1;
printf("thread1 waiting \n");
pthread_cond_wait(&cond1,&mutex1);
thread1waiting = 0;
}
else if((thread2waiting == 1) && abs(thread1count-thread2count)<1)
{
printf("signalling thread2\n");
pthread_cond_signal(&cond1);
}
pthread_mutex_unlock(&mutex1);
printf("Hey its thread 1 @ %d\n",thread1count);
}
}
void stupidfunction2(void *arg)
{
int i = 0;
for(i = 0;i<50;i++)
{
thread2count++;
pthread_mutex_lock(&mutex1);
if((thread2count-thread1count)>5)
{
thread2waiting = 1;
printf("thread2 waiting \n");
pthread_cond_wait(&cond1,&mutex1);
thread2waiting = 0;
}
else if((thread1waiting == 1) && abs(thread1count-thread2count)<1)
{
printf("signalling thread1\n");
pthread_cond_signal(&cond1);
}
pthread_mutex_unlock(&mutex1);
printf("Hey its thread 2 @ %d\n",thread2count);
}
}
OUTPUT:
Hey its thread 2 @ 1
Hey its thread 2 @ 2
Hey its thread 2 @ 3
Hey its thread 2 @ 4
Hey its thread 2 @ 5
thread2 waiting
Hey its thread 1 @ 1
Hey its thread 1 @ 2
Hey its thread 1 @ 3
Hey its thread 1 @ 4
Hey its thread 1 @ 5
signalling thread2
Hey its thread 1 @ 6
Hey its thread 1 @ 7
Hey its thread 1 @ 8
Hey its thread 1 @ 9
Hey its thread 1 @ 10
Hey its thread 1 @ 11
我不明白第一个错误 - 当第一个线程正在检查它的条件时,另一个线程不能进入临界区,那么第一个线程如何错过一个信号呢?你的行为意味着什么在允许的范围内?不是cond.signal应该立即唤醒,并将其置于就绪队列或锁定队列中。 – dasman 2011-01-11 09:20:50