Terry Li
Terry Li

Reputation: 17268

Given a thread id, how to decide it's still running or not on Windows

On linux, we have pthread_kill() to do this. I'm trying to find a Windows counterpart for it.

In other words, given a thread id, is there a way to decide whether the thread is still running or not?

GetExitCodeThread() is the closest I've found, however, it needs thread handle rather than thread id as its parameter.

Upvotes: 1

Views: 2267

Answers (2)

André Caron
André Caron

Reputation: 45239

In short, no, there isn't. You can determine whether a thread with the given identifier exists or not. However, you fundamentally can't determine that the thread you used to refer to using the given ID is still running or not. That's because the thread ID will be recycled after the thread completes.

To track a thread's lifetime, you need to get a thread handle, which will allow you to keep the thread alive for as long as you need. Think of it as a strong VS. weak reference thing. You can use OpenThread() to get a handle to a thread given its ID. You should do this ASAP after you get the ID, then always use the thread handle.

Upvotes: 2

James McNellis
James McNellis

Reputation: 355009

You should not use a thread id for this purpose: thread ids can be reused, so if you get a thread id, then that thread exits, another thread can be started with that same thread id.

The handle does not have this problem: once a thread terminates, all handles to that thread will reflect the terminated state of the thread.

You can obtain a handle for a thread with a given id using OpenThread; you can then pass that handle to GetExitCodeThread to determine whether the thread has exited.

Upvotes: 6

Related Questions