温馨提示×

Linux中pthread_self函数怎么用

小亿
94
2023-12-05 15:38:35
栏目: 智能运维

在Linux中,pthread_self函数用于获取当前线程的线程ID(Thread ID)。

使用pthread_self函数的步骤如下:

  1. 包含头文件 #include <pthread.h>
  2. 声明一个变量来保存线程ID,类型为 pthread_t
  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格式化说明符。

编译并运行上述示例代码,将会输出当前线程的线程ID。

0