c++ - pthreads 线程的唯一常量标识符?

标签 c++ multithreading pthreads

我假设 pthread_t 在其整个生命周期中 - 对于给定的线程 - 保持不变,但我的实验似乎证明这个假设是错误的。如果给定线程的 id 在其生命周期内不保持不变,我如何存储一个 pthread_t 以便另一个线程可以使用 pthread_join 阻塞直到该线程完成?

出于其他原因,了解如何获取线程的唯一标识符对我来说很有用,我可以将它来回转换为 pthread_t。有办法做到这一点吗?

那里有很多有用的信息,但我很难确定这些问题的有用答案。 如果能得到任何帮助/建议,我将不胜感激!

编辑:另外,我不确定为什么,但在每个新线程(在线程函数内)的前面添加 sleep(1) 并休眠 1 秒时,一切似乎都按预期工作。这可能像吸管一样抓取,但是 pthread_t 值会不会在新线程启动期间瞬间发生变化??

最佳答案

您不能依赖于 pthread_t 是唯一的,但您可以使用 pthread_equal() 来确定两个线程 ID 是否引用同一个线程。

NAME
     pthread_equal -- compare thread IDs

SYNOPSIS
     #include <pthread.h>

     int
     pthread_equal(pthread_t t1, pthread_t t2);

DESCRIPTION
     The pthread_equal() function compares the thread IDs t1 and t2.

RETURN VALUES
     The pthread_equal() function will return non-zero if the thread IDs t1 and t2
     correspond to the same thread. Otherwise, it will return zero.

关于c++ - pthreads 线程的唯一常量标识符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1052489/

相关文章:

c++ - 如何在 ZMQ 中为 (X)PUB/(X)SUB 消息传递实现代理/代理?

c++ - GetWindowText 故障

c - 附加到线程内的文件中

c++ - 文本文件中的行未正确分配到二维数组中

java - 如何将 Boost::make_recursive_variant 对象转换为字符串?

multithreading - 未处理的异常会停止Winform应用程序中的所有线程吗?

java - 我怎样才能使这个计算更快?

java - 模拟具有 setListener(...) 的依赖项

c - 互斥锁和pthread_join的区别

c - Helgrind 报告单线程上的数据争用