嗨 當我運行下面的代碼時,我發現信號線程在另一個線程開始之前會繼續運行很長時間......爲什麼會這樣呢?是不是被喚醒的線程應該在信號發佈者釋放鎖後立即運行?或者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