Reputation: 960
I am creating a shared library, with a class that creates a thread in its constructor which runs it until the destructor is called. All methods of this class are thread-safe. Something like this:
class NetworkRPCConnection {
std::thread t;
public:
NetworkRPCConnection() : t([](){maintain_connection();}) {}
~NetworkRPCConnection(){close_connection(); t.join();}
}
This works fine, but is it bad practice to create a thread in a shared library? Is it worth mentioning in the API documentation, or is it better to hide this implementation detail?
Upvotes: 4
Views: 3236
Reputation: 28070
In general it's best to avoid creating threads in shared libraries, but there are circumstances where it is OK - but in these cases, you really do need to document it in your API.
The reason you need to document it is that threads can interact in hard to predict ways with certain operations - notably fork()
and signals; this makes it impossible to completely "hide" the thread as an implementation detail, because the library user needs to be aware of it.
As for why it's better not to create threads: usually the user of the library has a better idea of their threading model - for instance, they may already have a thread that the work could be done in, so creating another one only creates extra overhead (and constrains their implementation). But if you know the requirements of the library's user very well, and know that an exclusive thread is needed, and can take care of all aspects of the thread's lifetime - then it may be OK to create and manage the thread yourself - but, as mentioned above, you definitely do need to document it.
Upvotes: 8