pthread_join() - スレッド終了の待機

標準

標準/拡張機能 C/C++ 依存項目

POSIX.4a
Single UNIX Specification、バージョン 3

両方

POSIX(ON)

形式

#define _OPEN_THREADS
#include <pthread.h>

int pthread_join(pthread_t thread, void **status);
SUSV3:
#define _UNIX03_THREADS
#include <pthread.h>

int pthread_join(pthread_t thread, void **status);

機能説明

呼び出しスレッドが、ターゲット thread の終了を待機できるように します。

pthread_t は、スレッドを一意的に識別する場合に使用される データ型です。これは pthread_create() によって戻され、スレッド ID を必要とする アプリケーションで使用されます。

status には、pthread_exit() の一部として終了スレッドが 渡す status 引数へのポインターが入ります。終了スレッドが戻りで終了した場合には、status には戻り値を指す ポインターが含まれています。スレッドが取り消された場合には、status は -1 に設定される ことがあります。

戻り値

正常に実行された場合、pthread_join() は 0 を戻します。

正常に実行されなかった場合、pthread_join() は -1 を戻して、errno を次のいずれかの 値に設定します。
エラー・コード
説明
EDEADLK
デッドロックが検出されました。これは、ターゲットが直接または間接に現行スレッドに結合したときに発生します。
EINVAL
thread によって指定された値は無効です。
ESRCH
thread によって指定された値は、切り離し解除のスレッドを指して いません。
注 :
  1. pthread_join() が正常に戻る場合、ターゲット・スレッドは切り離されています。
  2. 複数のスレッドで pthread_join() を使用して、同じターゲット・スレッドの終了を待機することはできません。 あるスレッドがターゲット・スレッドについて pthread_join() を 正常に発行したあと、別のスレッドが同じターゲット・スレッドについて pthread_join() を発行すると、2 番目の pthread_join() は 失敗します。
  3. pthread_join() を呼び出すスレッドが取り消されると、ターゲット・スレッドは切り離されません。

Single UNIX Specification、バージョン 3 の特殊な動作: 正常に実行されなかった場合、pthread_join() はエラーを示すエラー番号を戻します。

CELEBP32
⁄* CELEBP32 *⁄
#define _OPEN_THREADS
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>

void *thread(void *arg) {
  char *ret;
  printf("thread() entered with argument '%s'¥n", arg);
  if ((ret = (char*) malloc(20)) == NULL) {
    perror("malloc() error");
    exit(2);
  }
  strcpy(ret, "This is a test");
  pthread_exit(ret);
}

main() {
  pthread_t thid;
  void *ret;

  if (pthread_create(&thid, NULL, thread, "thread 1") != 0) {
    perror("pthread_create() error");
    exit(1);
  }

  if (pthread_join(thid, &ret) != 0) {
    perror("pthread_create() error");
    exit(3);
  }

  printf("thread exited with '%s'¥n", ret);
}
出力:
thread() entered with argument 'thread 1'
thread exited with 'This is a test'

関連情報