两种不同的pthread库

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;
  1. void* p:这个成员是一个指针类型,用来指向实际的对象。这个指针可以指向任何类型的对象或数据。
  2. 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;
}

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值