pthread_self関数の使い方をLinuxで教えてください

Linuxでは、pthread_self関数は現在実行中のスレッドの識別子(スレッドID)を取得するために用いられます。

pthread_self 関数を使用する手順:

  1. #include
  2. スレッドID
  3. pthread_self関数を呼び出し、返却されるスレッドIDを宣言された変数に格納する。

次にサンプルコードを示します。

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

void* threadFunc(void* arg) {
    pthread_t tid = pthread_self();
    printf("Thread ID: %lu\n", tid);
    return NULL;
}

int main() {
    pthread_t tid;
    pthread_create(&tid, NULL, threadFunc, NULL);
    pthread_join(tid, NULL);
    return 0;
}

上記例の_pthread_self_は、実行中のスレッドのIDを取得するもので、現在のスレッドのIDを出力するスレッドを作っています。

pthread_self関数が返すスレッドIDはunsigned long int型なので、出力する際は%lu書式指定子を使用する必要があることに注意してください。

上記サンプルを実行すると、現在のスレッドの識別番号が表示されます。

bannerAds