Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I close zeromq socket explicitly in python?

Tags:

python

zeromq

In C/C++ like languages, closing zeromq socket explicitly is a must, which I understand. But in some higher level languages, such as php and python, which have garbage collection mechanism, do I need to close the sockets explicitly?

In php, there is no ZMQSocket::close() and in python, pyzmq's doc says socket.close() can be omitted since it will be closed automatically during garbage collection.

So my question is, do I need to manually close it or not?...

like image 603
Ji ZHANG Avatar asked Jan 26 '12 14:01

Ji ZHANG


Video Answer


1 Answers

It is always correct to close any I/O resources when you are done with them. The garbage collector will close them off eventually. It may close it immediately once the last reference goes out of scope. It may close it as your program is exiting. While you wait for it to do so, the resource remains open taking up memory, consuming file pointers, and eating up your system resources in general. For a small, short lived program this may not be a big issue, but if your software is long living or establishes a lot of connections, this will come back to hurt you.

The answer is: it depends. If your system is reliant on the socket getting closed, then you are safer closing them explicitly. If you are fine with the socket getting closed at some indeterminate future time, you can save yourself a little bit of coding time and simplify your program a bit by just letting the garbage collector handle it.

like image 192
Konstantin Tarashchanskiy Avatar answered Oct 22 '22 07:10

Konstantin Tarashchanskiy