How to free /destroy object created by PyTuple_New

Hrvoje Niksic hniksic at xemacs.org
Sun Apr 5 03:47:06 EDT 2009


[ You can also ask questions like this on the specialized capi-sig
  list; see http://mail.python.org/mailman/listinfo/capi-sig ]

grbgooglefan <ganeshborse at gmail.com> writes:

> In my case, my C application has multiple threads & they are accessing
> a single Python Interpreter which was initialized by 1st main thread.
> In that case also, do I need to use PyGILState_Ensure/
> PyGILState_Release APIs?

Yes.  There is a single GIL that needs to be held even if each thread
has a different interpreter.

> Can I have a Python interpreter per thread so that I won't have
> issues of some data inside Python interpreters being gettint
> accidently overwritten/ freed by other thread?

You can have a separate interpreter per thread, but they will still
need to be synchronized using the GIL because even separate
interpreters share some global data, such as C-level global variables.

> Will Py_DECREF release the items set in that tuple using call to
> PyTuple_SetItem? Or do I need to separately call Py_DECREF for them
> also?

A single Py_DECREF on the tuple will call Py_DECREF on all the
contained objects.  This principle applies to all containers.

> What is correct sequence for calling Py_DECREF & Py_INCREF?

If you receive a "new" reference, you don't need to initially incref
it.  You need to call DECREF when you're done with the object,
i.e. when it stops being accessible for you (for example because you
replaced it with another object or NULL in your C-level data
structure).

> If I dont call Py_DECREF, will that object (PyTuple) not get freeed
> at all, causing memory leak?

Yes, and additionally it causes objects inside it to leak as well.



More information about the Python-list mailing list