2017-10-03 8 views
0

私はthread1,2,3,4によって実行される関数を持っています.... thread1が関数にアクセスすると、私は他のスレッドを待つためにthread_condを使います。 thread1がその仕事をしたら、私は同じcondにthread_signalを送ります。 Thread2が関数を実行しています。しかし、実行が終了すると、他のスレッドはその関数にアクセスしません。スレッド2,3,4が同じ信号をthread1から待つ方法を教えてください。

「仕事をして」私

#include<stdio.h> 
#include<unistd.h> 
#include<pthread.h> 

int limit = 0; 
pthread_mutex_t mutex[100]; 
pthread_cond_t cond[100]; 
pthread_t tid[100]; 

void *enter() 
{ 
    if (limit == 1) 
    { 
     printf("waiting\n"); 
     pthread_cond_wait(&cond[1],&mutex[1]); 
    } 
    gotofunction(); 
} 

void gotofunction() 
{ 
    limit++; 
    /* Do work */ 
    printf("Doing work\n"); 
    sleep(1); 
    limit--; 
    printf("Going to give signal\n"); 
    pthread_cond_signal(&cond[1]); 
} 

int main() 
{ 
    int n,i; 
    scanf("%d",&n); 
    for (i=0;i<100;i++) 
    { 
     pthread_mutex_init(&mutex[i], NULL); 
     pthread_cond_init(&cond[i], NULL); 
    } 
    for (i=0;i<n;i++) 
    { 
     pthread_create(&tid[i], NULL, enter, NULL); 
     sleep(0.5); 
    } 
    for (i=1;i<=n;i++) 
    { 
     pthread_join(tid[i], NULL); 
    } 
} 

基本的にはスレッド1版画「仕事をしている」 スレッド2プリント が次に何が他のスレッド

+0

'pthread_cond_signal'は、* one *(ランダム)スレッドのみを通知します。たとえば、次のようなマニュアルページを読んでください。 'pthread_cond_signal'、他の関数については教えてくれませんか?おそらく1つの[*ブロードキャスト*](http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_broadcast.html)シグナル? –

+0

@Someprogrammerdude私はブロードキャストがすべてのスレッドを起動させると思う。スレッドのうちの1つだけを目覚めさせ、その作業をして、もう1つのスレッドを起動させたいとします – user7693981

+1

おそらく 'pthread_cond_signal'の*チェーン*でしょうか?スレッドがシグナルの後に起動すると、スレッドは 'pthread_cond_signal'を呼び出します。 –

答えて

0

ために起こりませんあなたはpthread_cond_wait()に渡されたミューテックスを持っている必要があります助けてくださいあなたがそれを呼んだときにロックされています。そのミューテックスは、条件変数がペアになっている条件(この場合はlimit == 1がその条件である)をチェックして変更している間も、ロックされている必要があります。

条件変数が実際には真でない状態で起きる可能性があるので、while (condition) { pthread_cond_wait() }if (condition)ではなく)パターンも使用する必要があります。

次のようになり、作業をシミュレートしながら、limitへのアクセスの周りにmutexをロックし、ロックを解除するようにコードを変更する:あなただけ、あなたは1の制限に対してチェックするときもちろん

void *enter() 
{ 
    pthread_mutex_lock(&mutex[1]); 
    while (limit == 1) 
    { 
     printf("waiting\n"); 
     pthread_cond_wait(&cond[1],&mutex[1]); 
    } 
    gotofunction(); 
    pthread_mutex_unlock(&mutex[1]); 
    return NULL; 
} 

void gotofunction() 
{ 
    limit++; 
    pthread_mutex_unlock(&mutex[1]); 

    /* Do work */ 
    printf("Doing work\n"); 
    sleep(1); 

    pthread_mutex_lock(&mutex[1]); 
    limit--; 
    printf("Going to give signal\n"); 
    pthread_cond_signal(&cond[1]); 
} 

ができ代わりにプレーン・ミューテックスを使用してください。ただし、このスキームを拡張して、条件をwhile (limit >= N)に変更することによってN個のスレッドが同時に作業を実行できるようにすることができます。

関連する問題