こんにちは 次のコードを実行すると、他のスレッドが起動する前に、信号スレッドが長時間実行されていることがわかります。なぜですか?シグナルがロックを解除すると直ちに実行される目覚ましスレッドではありませんか?あるいは、スリープしているスレッドをレディキューに戻すのに時間がかかりますか?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
'volatile'は正しいpthreadsコードには必要ありません。必要なsyncrhonisation関数(例えば、 'pthread_mutex_lock()')はコンパイラの障壁を意味します。 – caf