osx上的小线程ID

Small thread ID on osx

本文关键字:线程 ID osx      更新时间:2023-10-16

是否有一个函数返回一个类似于gettid()的pthread ID ?我尝试了pthread_threadd_np (), pthread_self(),但这些太长了。我需要一个最多32位长的tid

这是一个可以在OSX和任何其他支持gnu扩展__thread的c++11系统上工作的策略(我只使用这个,因为苹果的clang分支不实现标准的thread_local)

#include <iostream>
#include <cstdint>
#include <atomic>
#include <thread>
#include <future>
static std::int32_t current_id()
{
    static std::atomic<std::int32_t> next_id { 0 };
    static __thread std::int32_t id = 0;
    if (id == 0)
        id = ++next_id;
    return id;
}
void emit_id()
{
    static std::mutex m;
    std::unique_lock<std::mutex> l(m);
    std::cout << "thread id = " << current_id() << std::endl;
}
int main()
{
    auto t = std::thread([] { emit_id(); });
    auto f = std::async(std::launch::async, [] { emit_id(); });
    emit_id();
    f.get();
    t.join();
}

示例输出:

thread id = 1
thread id = 2
thread id = 3

剧情简介:

每个id都是thread_local int32,初始值为0(无效id)。

第一次需要id时,下一个可用id将使用静态原子顺序生成。

一种可能的方法是维护一个pthread_t值的静态表,并使用一些函数来管理它。你的get_short_tid函数调用pthread_self来获得pthread_t的值。然后在表中搜索,如果找到,则返回相应的短ID。如果没有找到,它就为它分配一个新条目,在那里输入它,分配一个新的短ID并返回。您需要一些定期的方法来过期过期的条目。每隔一段时间,get_short_tid函数可以遍历表,并在每个pthread_t上使用信号为0的pthread_kill。所有产生错误的数据都将从表中删除。你的ID生成可以只是一个32位的包装计数器;这取决于您是否确保这足以使您的应用程序避免ABA_problem。

在Mac上,<pthread.h>定义

mach_port_t pthread_mach_thread_np(pthread_t);

显示内核所知道的线程对象的底层无符号整数id(32位)。这些值通常很低,但与Linux gettid()的重要区别在于,主线程的getpid()pthread_mach_thread_np(pthread_self())不会返回相同的值。