pthread库分为两种,一种是Windows平台的pthread库(pthread for win32),另一种是Linux平台的pthread库(mingw-w64提供的gcc编译器(posix版本)提供的pthread)。其中两个库的实现有些许不同,例如对于pthread_t线程id的定义不同
Linux平台实现的pthread库实现的pthread_t如下所示:
typedef uintptr_t pthread_t;
uintptr_t是一个整数类型,足够大以容纳指针和地址的无符号整数类型,对于线程id的获取函数原型如下:
pthread_t pthread_self(void);
应用到代码中获取id的实例代码如下:
#include <pthread.h>
#include <stdio.h>
void* thread_function(void* arg) {
pthread_t my_id = pthread_self();//获取线程id
printf("Thread ID is %lu\n", my_id);
// 其它操作
return NULL;
}
int main() {
pthread_t tid;
pthread_create(&tid, NULL, thread_function, NULL);
// 等待线程结束
pthread_join(tid, NULL);
return 0;
}
Windows平台中的pthread for win32对于pthread_t实现为一个结构体,源代码如下(不同版本可能有些许不同):
typedef struct
{ void * p; /* Pointer to actual object */
#if __PTW32_VERSION_MAJOR > 2
size_t x; /* Extra information - reuse count etc */
#else
unsigned int x; /* Extra information - reuse count etc */
#endif
} ptw32_handle_t;
typedef ptw32_handle_t pthread_t;
void* p
:这个成员是一个指针类型,用来指向实际的对象。这个指针可以指向任何类型的对象或数据。size_t x
或unsigned int x
: 这个成员是用来存储额外信息的。在特定情况下,可能需要存储一些附加的信息,比如重用计数等。根据条件编译的不同,可能会选择使用size_t
或者unsigned int
类型。
在 Windows 环境下,可以使用 pthread_getw32threadid_np
函数来获取当前线程在 Windows 线程环境下的 id。这个函数返回一个 DWORD
类型的值,代表当前线程的 ID。示例如下:
#include <pthread.h>
#include <stdio.h>
#include <windows.h>
int main() {
DWORD tid = pthread_getw32threadid_np(pthread_self());
printf("当前线程的Windows环境下的ID为:%lu\n", tid);
return 0;
}