-1

I have a class that handles zmq messages. If a message is received the class notifies its observer. This observer than creates a boost::thread which resolves the received zmq message. After the message is resolved the observer starts another thread which than executes the resolved command.

So there is one observer which creates a thread for each incoming message. How do I ensure that the created threads are safely destroyed after they resolved the message ? Also what happens with the thread that is started within the resolver thread. That thread also has to be destroyed safely in the end.

I think there is a simple solution for this but I lack the experience with multi-threading and don't no what to google ...

Edit: Do I even have to care about threads when they returned a value by themselves ?

A. Osterthun
  • 175
  • 1
  • 3
  • 18
  • I don't know boost, but creating a new thread for every incoming message seems wasteful. Why not use a [thread pool](https://stackoverflow.com/q/19500404/801894)? – Solomon Slow Aug 29 '17 at 18:42
  • Since C++11 there is a standard `std::thread`. Why not use that? It's way better documented and is available out of the box on any conforming compiler. – rustyx Aug 29 '17 at 19:26

1 Answers1

0

Threads can be detached or joined. If you join, your main thread is going to block until its complete. If you detach, your thread runs until its finished or your application terminates. Assuming the latter isn't going to happen, this is fine.

Regarding boost::threads specifically (by the way, do you have access to std::thread - introduced C++11)..

When the boost::thread object that represents a thread of execution is destroyed the thread becomes detached. Once a thread is detached, it will continue executing until the invocation of the function or callable object supplied on construction has completed, or the program is terminated. A thread can also be detached by explicitly invoking the detach() member function on the boost::thread object. In this case, the boost::thread object ceases to represent the now-detached thread, and instead represents Not-a-Thread.

In order to wait for a thread of execution to finish, the join() or timed_join() member functions of the boost::thread object must be used. join() will block the calling thread until the thread represented by the boost::thread object has completed. If the thread of execution represented by the boost::thread object has already completed, or the boost::thread object represents Not-a-Thread, then join() returns immediately. timed_join() is similar, except that a call to timed_join() will also return if the thread being waited for does not complete when the specified time has elapsed.

As an aside, unless this application is for a small number of connections, think a bit about whether you really need a thread per request. There is some overhead (10s of microsends and by default sometimes between 1-2MB of memory).

Josh
  • 12,602
  • 2
  • 41
  • 47