osx上的小线程ID

时间:2016-09-02 14:44:04

标签: c++ macos pthreads

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

这是一个适用于OSX和支持gnu扩展__thread的任何其他c ++ 11系统的策略(我之前只使用过这个,因为Apple的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,它最初为零(无效的id)。

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