[Pythonmidi-devel] Deallocating resources using destructors
Status: Pre-Alpha
Brought to you by:
regebro
From: Donovan P. <dp...@ul...> - 2004-11-04 18:31:56
|
On Oct 29, 2004, at 3:59 AM, Lennart Regebro wrote: > A big problem popped up yesterday: > > It turns out that a Python objects __del__ does not necessarily get > called when a program exits. I knew this once, but I had forgotten it. > > This means the ports does not get closed unless you specifically call > close on the objects. This is major bug for a Python program, where > the garbage collection is supposed to make sure you never have to > deallocate resources. It's also makes my computer crash. Not > immediatly mind you, but say, 30 minutes later, or so. XP just > silently goes *poof* and reboots. NOT fun! (It's probably crappy MIDI > drivers that cause this). > > The solution to this is supposed to be to write the whole python > object in C, instead of just wrapping the c methods in a python > object. C objects do get properly deallocated when a program exits, > I'm told. Now, that means that the C code suddenly gets MUCH more > complex (and it wasn't exactly trivial before either) so I'm gonna > look at doing this in Pyrex. I'm not sure where you got the idea that C objects get deallocated when a program exits. It's true that stack-local variables of simple type such as integers or chars will be automatically released because the entire stack is released when the program exits, but this has nothing to do with externally allocated resources such as memory allocated with malloc, opened file handles, or opened midi ports. In fact, it is absolutely impossible to arrange for some code to be invoked upon the unexpected termination of your c program. In general, relying on destructors to free externally allocated resources is a bad, bad idea. Rather than attempting to rewrite your program in C, I would suggest you just rewrite the python portion to explicitly free resources in case of unexpected error (using a try: finally: block, for example.) dp |