1

Is there a way to determine if a thread is still running? I cannot use std::future and std::async for several reasons.

I thought of some kind of join with timeout, e.g. try to join a thread for 3 seconds, if it succeeds, the thread is considered finished, otherwise it is considered running.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
Nidhoegger
  • 4,973
  • 4
  • 36
  • 81
  • I guess you want `joinable`. Look up the documentation: http://www.cplusplus.com/reference/thread/thread/joinable/ –  Nov 26 '15 at 16:52
  • 1
    If the function object invoked by the thread is under your control, the simplest option is to set a flag associated with the `std::thread` when the thread finishes. Checking if the thread is still alive would then simply check the current state of the flag. – user4815162342 Nov 26 '15 at 16:54
  • But `joinable` will only tell me if the thread is joinable or not. Even when the thread has finished execution. Or am I wrong? – Nidhoegger Nov 26 '15 at 16:55
  • @user4815162342: I came up with that solution, too. I should have stated in my question that there are many many threads running (its a server application, each client has an own thread) – Nidhoegger Nov 26 '15 at 16:56
  • 1
    Many threads should not be a problem in itself - after all, you only need a single bit of state per thread. The problem is if clients are creating threads without your being aware of it - but in that case, how are you getting their `std::thread` handles? – user4815162342 Nov 26 '15 at 17:00
  • I have a pointer to every thread that has been created... – Nidhoegger Nov 26 '15 at 17:03
  • If you can't modify the code that creates the threads, or the functions they are running, only having access to the pointers is not very useful. – user4815162342 Nov 26 '15 at 17:26

1 Answers1

1

The closest you can get is std::thread::joinable(). To cite from the reference:

Checks if the thread object identifies an active thread of execution. Specifically, returns true if get_id() != std::thread::id(). So a default constructed thread is not joinable.
A thread that has finished executing code, but has not yet been joined is still considered an active thread of execution and is therefore joinable.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • 8
    This will not work reliably since a `std::thread` that has finished executing but was not yet detached or joined is still joinable. You even cited this fact. – sigy Jul 12 '17 at 12:22