2017-08-07 2 views
0

マルチスレッドを研究しているうちに、次のコードを書きましたが、出力は画面上に表示されませんでした。私はここで間違って何をしていますか?以下のコードで何が問題になっていますか?スレッドXによって変更された期待XスレッドXで変更されたFunc 2

しかし、画面には何も見えず、プログラムは終了しません。

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

pthread_mutex_t globalMutex[2]; 
pthread_cond_t globalCondVar[2]; 

void *threadFunc1(void *args) 
{ 
    pthread_mutex_lock(&globalMutex[0]); 
    pthread_cond_wait(&globalCondVar[0], &globalMutex[0]); 
    printf("X modified by threadFunc 1\n"); 
    pthread_mutex_unlock(&globalMutex[0]); 
} 

void *threadFunc2(void *args) 
{ 
    pthread_mutex_lock(&globalMutex[1]); 
    pthread_cond_wait(&globalCondVar[1], &globalMutex[1]); 
    printf("X Modified by threadFunc 2\n"); 
    pthread_mutex_unlock(&globalMutex[1]); 
} 

int main() 
{ 
    pthread_t thread[2]; 

    pthread_mutex_init(&globalMutex[0], NULL); 
    pthread_mutex_init(&globalMutex[1], NULL); 
    pthread_cond_init(&globalCondVar[0], NULL); 
    pthread_cond_init(&globalCondVar[1], NULL); 

    pthread_create(&thread[0], NULL, threadFunc1, NULL); 
    pthread_create(&thread[1], NULL, threadFunc2, NULL); 

    pthread_cond_signal(&globalCondVar[0]); 
    pthread_cond_signal(&globalCondVar[1]); 

    pthread_join(thread[1], NULL); 
    pthread_join(thread[0], NULL); 

    pthread_cond_destroy(&globalCondVar[0]); 
    pthread_cond_destroy(&globalCondVar[1]); 
    pthread_mutex_destroy(&globalMutex[0]); 
    pthread_mutex_destroy(&globalMutex[1]); 

    return 0; 
} 
+2

信号が早過ぎる可能性があります。 main()シグナルの前にsleep()をスローします。 –

+1

また、スレッド関数は何かを返す –

+0

何@ BjornA。言った。ちょっと待って、セマフォーで置き換えてください。 –

答えて

1

条件変数はないイベントです。 mutexによって保護された実際のブール条件で使用するように設計されています。

(Init) 
    condition = false 

    (Signal) 
    lock mutex 
    condition = true 
    signal condvar 
    unlock mutex 

    (Wait) 
    lock mutex 
    while not condition: 
     wait condvar 

これは、条件変数を使用する標準的な方法です。

関連する問題