Is it a bad practice to create a stream in a shared library?

I am creating a shared library with a class that creates a thread in its constructor that runs it before the destructor is called. All methods of this class are thread safe. Something like that:

class NetworkRPCConnection {
  std::thread t;
public:
  NetworkRPCConnection() : t([](){maintain_connection();}) {}
  ~NetworkRPCConnection(){close_connection(); t.join();}
}

      

This works great, but is it really bad practice to create a stream in a shared library? Is it worth mentioning in the API documentation, or is it better to hide this implementation detail?

+3


source to share


1 answer


In general, it's best to avoid creating streams in shared libraries, but there are circumstances where it's okay - but in those cases, you really need to document it in your API.

The reason you need to document this is because threads can interact in difficult-to-predict ways with certain operations — especially fork()

signals; this makes it impossible to completely "hide" the stream as an implementation detail, because the user of the library must be aware of this.



As for why it is better not to create threads: Usually the user of the library is better at understanding their threading model - for example, they may already have a thread to work with, so creating another creates additional overhead (and limits their implementation) ... But if you are well aware of the library user's requirements and know that an exclusive thread is needed and can take care of all aspects of the thread's lifecycle, then it might be good to create and manage the thread yourself, but since the one mentioned above, you definitely need to document it.

+7


source







All Articles