Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get thread object by id?

Let's say that some thread has std::thread::id myId of some other thread. Now I want to retrieve the std::thread object associated with myId so I can .join() it. Is it possible in std? Or do I have to track it manually?

like image 400
freakish Avatar asked Oct 18 '22 15:10

freakish


1 Answers

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. 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. In other words you can cast that to pthread_t and pass it to pthread_join. thestd::thread object associated with it should behave as it would if you had called join() on it.

Example program (tested on 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

thread::join failed: No such process

As you can see pthread_join() did not return an error the first time it was called indicating that indeed the thread was joined. The second time it returns ESRCH because the thread was already joined; same as the 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; I did not detect any errors when running with Asan/Ubsan/Tsan; YMMV.

like image 89
Brad Allred Avatar answered Oct 21 '22 01:10

Brad Allred