/*********************************************
* @brief 获取当前线程的 ID
* @return 当前线程的 ID
********************************************/
thrd_t thrd_current();
!subtitle:说明
获取当前线程的 ID。
线程 ID 的类型 thrd_t 是一个不透明类型,无法直接进行查看,只能通过 thrd_equal 进行相等判断。
!subtitle:参数
无
!subtitle:返回值
当前线程的 ID
#include <stdio.h>
#include <threads.h>
// 线程入口函数
int func(void* data)
{
thrd_t main_id = *(thrd_t*)data; // 参数传入主线程 ID
thrd_t current_id = thrd_current(); // 获取当前线程 ID
if (thrd_equal(main_id, current_id))
{
printf("当前线程是主线程\n");
}
else
{
printf("当前线程是子线程\n");
}
return 0;
}
int main(void)
{
// 获取主线程 ID
thrd_t main_id = thrd_current(); // 获取当前线程 ID
// 直接调用 func
func(&main_id);
// 创建线程调查 func
thrd_t th;
thrd_create(&th, func, &main_id);
// 等待线程结束
thrd_join(th, NULL);
return 0;
}
运行结果:
当前线程是主线程
当前线程是子线程
C17 standard (ISO/IEC 9899:2018):
7.26.5.2 The thrd_current function (p: 279)
C11 standard (ISO/IEC 9899:2011):
7.26.5.2 The thrd_current function (p: 383)