C 中的 pthread_self()


这里我们将看到 pthread_self() 在 C 中的作用。pthread_self() 函数用于获取当前线程的 ID。此函数可以唯一标识现有线程。但是如果存在多个线程,并且其中一个线程已完成,则可以重复使用该 ID。因此,对于所有正在运行的线程,其 ID 都唯一。

示例

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* func(void* p) {
   printf("From the function, the thread id = %d
", pthread_self()); //get current thread id       pthread_exit(NULL);    return NULL; } main() {    pthread_t thread; // declare thread    pthread_create(&thread, NULL, func, NULL);    printf("From the main function, the thread id = %d
", thread);    pthread_join(thread, NULL); //join with main thread }

输出

From the main function, the thread id = 1
From the function, the thread id = 1

更新于: 30-7-2019

8000+浏览量

开启你的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.