简体   繁体   English

如何通过id获取线程对象?

[英]How to get thread object by id?

Let's say that some thread has std::thread::id myId of some other thread. 假设某些线程有一些其他线程的std::thread::id myId Now I want to retrieve the std::thread object associated with myId so I can .join() it. 现在我想检索与myId关联的std::thread对象,这样我就可以.join()了。 Is it possible in std ? std有可能吗? Or do I have to track it manually? 或者我必须手动跟踪它?

I don't recommend this if you can avoid it. 如果可以避免,我不建议这样做。 Its a bad design even on platforms where it will work. 即使在可以工作的平台上,它也是一个糟糕的设计。 I present it as an academic exercise to satisfy curiosity. 我把它作为一种学术运动来满足好奇心。

AFIK there is no standard way to do it. AFIK没有标准的方法来做到这一点。 If you don't require portability and you really want to do this... 如果你不需要便携性,你真的想这样做......

On some platforms (Mac and probably Linux for example) std::thread will just be a wrapper around the underlying pthread_t which you already have as it is the same as the std::thread::id you already have. 在某些平台上(例如Mac,可能是Linux), std::thread将只是你已经拥有的底层pthread_t的包装器,因为它与你已经拥有的std::thread::id相同。 In other words you can cast that to pthread_t and pass it to pthread_join . 换句话说,您可以将其pthread_tpthread_t并将其传递给pthread_join the std::thread object associated with it should behave as it would if you had called join() on it. std::thread与之相关联的对象应该表现为它会如果调用join()就可以了。

Example program (tested on macOS 10.13): 示例程序(在macOS 10.13上测试):

auto t1 = std::thread([]() {
    printf("Thread ran.\n");
});

auto id = t1.get_id();
pthread_t* ptr = (pthread_t*)&id;
int ret = pthread_join(*ptr, nullptr);
if (ret == 0) {
    printf("thread joined.\n");
}

ret = pthread_join(*ptr, nullptr);
if (ret != 0) {
    printf("error: %d\n", ret);
}

try {
    t1.join();
} catch (std::system_error& e) {
    printf("%s\n", e.what());
}

output: 输出:

Thread ran. 线程运行。

thread joined. 线程加入。

error: 3 错误:3

thread::join failed: No such process thread :: join失败:没有这样的过程

As you can see pthread_join() did not return an error the first time it was called indicating that indeed the thread was joined. 正如您所看到的, pthread_join()在第一次调用时没有返回错误,表明线程确实已加入。 The second time it returns ESRCH because the thread was already joined; 第二次返回ESRCH因为线程已经加入; same as the t1.join() . t1.join()相同。

Do note that t1.joinable() will still return true if the implementation is built to simply check that the pthread_t is non 0. The std::thread will be destroyed without error when it goes out of scope; 请注意,如果构建实现只是检查pthread_t是否为0, t1.joinable()仍将返回true。当std::thread超出范围时,它将被销毁而不会出错; I did not detect any errors when running with Asan/Ubsan/Tsan; 与Asan / Ubsan / Tsan一起跑步时,我没有发现任何错误; YMMV. 因人而异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM