osx上的小线程ID
Small thread ID on osx
是否有一个函数返回一个类似于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())
不会返回相同的值。
- 我应该在C++中打印线程 ID 吗?
- 我可以使用Qt线程ID为每个线程创建唯一的缓存吗?
- 这种基于线程 ID 的同步是否安全整洁?
- OpenMP:当我按线程 ID 访问共享变量时,我是否需要一个关键部分
- C 不同的线程在FreeBSD 10上具有相同的线程ID
- 如何获取正确的线程 ID 和值
- 调试器看到的输出线程 ID
- 是否可以向特定的线程 ID 发送信号?
- C++ 中 OpenMP 中的有序线程 ID
- 您可以在 OpenMP 中将特定线程 ID 分组到唯一的任务组中吗?
- 查找称为函数C 的线程ID
- 确定进程的输入线程 ID
- SetWindowShookex(WH_KEYBOARD)无法与线程ID一起使用
- 在性能方面获取线程 ID 是否昂贵
- 标准::线程::id的要求.可以雾化吗?
- 如何知道谁是给定线程 ID 的父线程
- 当OwningThread表示线程ID时,它为什么是HANDLE类型的CRITICAL_SECTION的成员
- 不确定我在提升日志中的线程 ID 是否正确
- 线程ID不存在的OpenThread
- 如果父线程 ID 没有作为pthread_create上的参数传入,是否可以从 C/C++ 中的线程中获取父线程 ID?