5

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?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
freakish
  • 54,167
  • 9
  • 132
  • 169

1 Answers1

3

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.

Community
  • 1
  • 1
Brad Allred
  • 7,323
  • 1
  • 30
  • 49
  • 1
    How can one update the `std::thread`'s `id`-member upon having joined the native thread without it? – Deduplicator Oct 01 '18 at 22:44
  • @Deduplicator in what way and for what purpose does it need to be updated? assuming the implementation in question the `id` is just a `pthread_t`. I already stated this wont be portable. – Brad Allred Oct 01 '18 at 22:49