LoginSignup
6
5

More than 5 years have passed since last update.

pthread_cond_wait の簡単なテスト

Last updated at Posted at 2018-03-15

pthread_cond_waitでpthread_cond_signalによってシグナルを受けるまで処理を待ちます。

SampleCondWait.cpp
#include <stdio.h>
#include <pthread.h>
#include <iostream>
#include <thread>

#define test_cond_wait

pthread_mutex_t mutex;
pthread_cond_t cond;
static void *thread1(void*);

int main(void)
{
    pthread_t thread_id = 0;

    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);

    if(pthread_create(&thread_id, NULL, thread1, NULL) < 0)
    {
      std::cout << "ERROR for creating thread " << std::endl;
      exit(1);
    }

#ifdef test_cond_wait
    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&cond, &mutex);
    pthread_mutex_unlock(&mutex);
#endif

   std::cout << "Main is working" << std::endl;

   if(pthread_join(thread_id, NULL) < 0)
   {
     std::cout << "ERROR for finishing thread " << std::endl;
     exit(1);
   }

   std::cout << "Main End" << std::endl;
}

void *thread1(void *arg)
{
   std::cout << "Thread is working" << std::endl;

#ifdef test_cond_wait
   pthread_mutex_lock(&mutex);
   pthread_cond_signal(&cond);
   pthread_mutex_unlock(&mutex);
#endif
}

以下はpthread_cond_waitを動作させた場合の実行結果

$ g++ -std=c++11 SampleCondWait.cpp -lpthread
$ ./a.out
Thread is working
Main is working
Main End

以下はpthread_cond_waitをプリプロセッサで無効にした場合の実行結果

$ g++ -std=c++11 SampleCondWait.cpp -lpthread
$ ./a.out
Main is working
Thread is working
Main End

pthread_cond_waitを使った場合、
pthread_createが呼ばれてthread1を作りMain文はpthread_cond_waitで、
thread1からpthread_cond_signalのシグナルを待ち受けます。
そのため、先に"Thread is working"が表示され、thread1が終了し、Main処理が終了します。

pthread_cond_waitを使わなかった場合、
pthread_createが呼ばれてthread1を作っている間にMain文の処理は進み、
"Main is working"を表示してpthread_joinでthread1が終了するまで待ちます。
そのため、後から"Thread is working"が表示され、Thread1が終了し、Main文が終了します。

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5