Cleaning up

When you code in a programming language such as Python or Java, you do not need to worry about memory management since these languages have built-in mechanisms to clean up the memory.

For example, Python uses reference counting when there are cycles in a reference chain of objects, which never gets freed and memory automatically gets cleaned up for you when you implement a ZeroMQ application in Python. So, you do not need to explicitly close a connection when coding a ZeroMQ application since it will be closed as soon as the reference count of the object becomes zero. However, we should note that this would not work on Jython, PyPy, or IronPython. Anyway, this is enough information on Python. Let's return to our main concern.

When you code in C, memory management is your responsibility. Otherwise you will have an unstable application, which will have memory leak problems.

You need to take care of sockets, messages, and contexts in ZeroMQ. There are a couple of things you need to consider to finish an application successfully:

  • As we have said earlier, you need to close the application by destroying the context using zmq_ctx_destroy(3). However, if there are some sockets open, zmq_ctx_destroy(3) will just wait there forever. Therefore, you need to close the sockets and then call zmq_ctx_destroy(3) to destroy the context.
  • zmq_ctx_destroy(3) will wait forever if there are connections or messages on the queue to be sent.
  • Whenever you have finished processing a message, you need to close it immediately by calling zmq_msg_close(3), otherwise your application may have memory leaks. You could think about it this way: when you leave your house, you close the door. You do not leave it open. Similar idea.
  • Do not open and close a lot of sockets. If you do so, it pretty much means you are doing something wrong and you will want to redesign your application from scratch.

You may wonder what happens if your application is a multithreaded application. Well, in that case, things get really complicated.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.230.82