mr_js
mr_js

Reputation: 1029

How to create a socket object using multiprocessing and pass it back to the parent process

I wish to create a sock.Socket object from a main program using multiprocessing to avoid blocking the main program if the socket is not available during the creation process. The socket gets created but can not be returned to the main program.

After some reading it seems that objects can not be shared between python processes. It there a possible design pattern to circumvent this? Is multiprocessing suitable for this application or should I be considering another approach?

Upvotes: 1

Views: 186

Answers (1)

Steve Barnes
Steve Barnes

Reputation: 28390

You should keep it really simple and have a socket handler thread which:

  1. Opens the Socket,
  2. Retains ownership of it,
  3. Handles it for your main program, i.e. on data arriving passes it to the parent via one of an event, pubsub or a callback,
  4. If the connection is lost either reopens it or lets the parent know and end cleanly,
  5. On shutdown closes the socket for you.

Then everything becomes non-blocking. This is a much cleaner design pattern especially if you use pubsub.

Upvotes: 1

Related Questions