0

I'm writing a server in C++ that consists of a master thread that accepts incoming requests, then spawning a new std::thread object to handle the task of responding to it.

This std::thread object goes into a list of threads, and I want to clean up this list periodically like this:

For each thread in the list:
  If the thread has finished executing:
    Call join on the thread
    Remove the thread object from the list

Now the challenge is how to determine if this thread (which is executing a void function) has hit the end or not. The joinable() function doesn't work because it returns true mid-execution as well as afterwards, and I only want my master thread to call join() if it's done, otherwise it's going to hang and wait for that child thread in serial rather than executing in parallel.

GenTel
  • 1,448
  • 3
  • 13
  • 19
  • There's no way in standard C++; solutions are platform specific. In WIndows use `if (WaitForSingleObject(thread.native_handle(), 0) == WAIT_OBJECT_0)`. – Jonathan Potter Jan 31 '19 at 11:19

1 Answers1

0

Well, your architecture choice is "thread per request", then you should respect some core facts about the side-effects.

  1. Thread execution is cheap, thread creation is not.
  2. Excessive amount of threads living simultaneously would waste your RAM for nothing.

Given that, you should not bother about "if the thread is alive". Better, you should use "thread pool" idiom where you mitigate both risks mentioned above:

  1. All threads in the pool are created in advance, then they live as long as the pool, just waiting for the next portion of code to execute.
  2. Like a cinema theaters, thread pools has limited amount of vacant seats so you always can predict how much resources your threads are hungry about.

So, your desired flow should be then:

For each thread in the list:
    Wait for a new request to process
    Get next request from the incoming queue
    Process it
Yury Schkatula
  • 5,291
  • 2
  • 18
  • 42