pthreadのスレッド識別子pthread t型

提供: C言語入門
移動: 案内検索
スポンサーリンク

pthreadのpthread_t型とは、スレッドのスレッド識別子(スレッドID)です。古い実装では、pthread_tは整数型でしたが、現在では、必ずしも整数とは限らず、構造体へのポインタということもあり得ます。FreeBSDでは、pthread_tは、struct pthreadのポインタ型です。

読み方

pthread_t
ぴーすれっど あんすこ てぃー

概要

pthread_createで呼び出し元に、pthread_t型のスレッド識別子(スレッドID)が返されます。スレッド自身は、自身のスレッド識別子をpthread_self()で取得できます。

ヘッダファイル

FreeBSD 10.0-RELEASE
/usr/include/sys/_pthreadtypes.h
Ubuntu 14.04 amd64
/usr/include/x86_64-linux-gnu/bits/pthreadtypes.h

ソースコード

FreeBSD 10.0-RELEASEの /usr/include/sys/_pthreadtypes.h の抜粋です。

/*
 * Forward structure definitions.
 *
 * These are mostly opaque to the user.
 */
struct pthread;
 
...
 
/*
 * Primitive system data type definitions required by P1003.1c.
 *
 * Note that P1003.1c specifies that there are no defined comparison
 * or assignment operators for the types pthread_attr_t, pthread_cond_t,
 * pthread_condattr_t, pthread_mutex_t, pthread_mutexattr_t.
 */
#ifndef _PTHREAD_T_DECLARED
typedef struct  pthread                 *pthread_t;
#define _PTHREAD_T_DECLARED
#endif

Ubuntuでは、以下の実装です。 Ubuntu 14.04の/usr/include/x86_64-linux-gnu/bits/pthreadtypes.h からの抜粋です。

typedef unsigned long int pthread_t;


スレッドIDを取得する pthreadid1.c の例

ソースコード pthreadid1.c

#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
 
void f1(void);
void f2(void);
 
int
main(int argc, char *argv[])
{
        pthread_t thread1, thread2;
        int ret1,ret2;
 
        ret1 = pthread_create(&thread1,NULL,(void *)f1,NULL);
        ret2 = pthread_create(&thread2,NULL,(void *)f2,NULL);
 
        if (ret1 != 0) {
                err(EXIT_FAILURE, "can not create thread 1: %s", strerror(ret1) );
        }
        if (ret2 != 0) {
                err(EXIT_FAILURE, "can not create thread 2");
                err(EXIT_FAILURE, "can not create thread 2: %s", strerror(ret2) );
        }
 
        printf("thread1: %p\n", thread1);
        printf("thread2: %p\n", thread2);
        ret1 = pthread_join(thread1,NULL);
        if (ret1 != 0) {
                err(EXIT_FAILURE, "can not join thread 1");
        }
 
        ret2 = pthread_join(thread2,NULL);
        if (ret2 != 0) {
                errc(EXIT_FAILURE, ret2, "can not join thread 2");
        }
 
        return 0;
}
 
 
void
f1(void)
{
        printf("%s: %p\n", __func__, pthread_self());
}
 
void
f2(void)
{
        printf("%s: %p\n", __func__, pthread_self());
}

コンパイル

cc  -lpthread pthreadid1.c -o pthreadid1

実行例

% ./pthreadid1
thread1: 0x801406800
thread2: 0x801406c00
f2: 0x801406c00
f1: 0x801406800

関連項目




スポンサーリンク