Re: [Cython] [cython-users] Calling gil-requiring function not allowed without gil
[second try in moving this discussion to cython-devel] Dag Sverre Seljebotn, 12.08.2011 08:50:
On 08/12/2011 06:44 AM, Robert Bradshaw wrote:
On Thu, Aug 11, 2011 at 5:53 AM, Dag Sverre Seljebotn <d.s.seljebotn@astro.uio.no> wrote:
On 08/11/2011 02:13 PM, Stefan Behnel wrote:
Dag Sverre Seljebotn, 11.08.2011 13:58:
On 08/11/2011 01:43 PM, Ting Zhou wrote:
here is my pyx file. When I compile it, it says "Calling gil-requiring function not allowed without gil" at calling dabs(x[i]). Why my dabs function is a gil-requiring function?
==================================== from cython.parallel import * import numpy as np cimport numpy as np cimport cython
cdef double dabs(double x):
This should be
cdef double dabs(double x) nogil:
Note that Cython cannot infer this automatically. Even a trivial function may require an exclusive global lock for some reason, and it's common to use the GIL for that. So the programmer must be explicit here.
Are you still against this mini-CEP?:
with cython.global_lock(): ...
Where global_lock() is GIL-requiring noop.
Just reading this, it's not immediately obvious what this means. (I thought at first this was different syntax for "with gil"...)
True. "cython.synchronized"? The synchronized keyword in Java does not quite the same thing but almost.
This
a) Improves code readability vastly. Having a critical section take effect because of the *lack* of a keyword is just very odd to anyone who's not shoulder deep in CPython internals
I'm not following you here. The only way to run into this is if you have explicitly release it. Presumably you can learn both keywords at the same time. Perhaps extern function could be nogil by default.
I'll try to explain again. Consider code like this:
cdef call_c(): magic_c_function(3)
This code is perfectly fine even if magic_c_function is not reentrant -- but that's hardly well documented! So it's conceivable that another programmer comes along (who doesn't know the C library well) and decides that "somebody has just been too lazy to add the nogil specifier" and slaps it on -- at which point you have a bug.
This is more to the point in creating readable code IMO:
cdef call_c(): with cython.synchronized(): magic_c_function(3)
I think I'm as confused as Robert here. Is that the GIL or some separate lock? If the latter, where would that lock be stored? Module-wide? While there are certainly use cases for that, I think it's much more common to either a) use the GIL or b) use an explicit lock at some well defined point, e.g. at an object or class level. I don't think we disagree when I say that locking should be explicit, but that includes the "thing" that keeps the lock during its lifetime.
Also, consider your classical race conditions:
cdef init(): global resource if resource == NULL: resource = malloc(sizeof(resource_t)) ...
This is safe code.
Well, it's safe code as long as there is no Python code interaction in between. Calling back into the interpreter may trigger a thread switch. Admittedly, this is not obvious and tends to introduce bugs. I learned that the hard way in lxml, actually twice. If your "synchronised" directive refers to the GIL, then it would suffer from that problem as well. I think that's very undesirable for an explicit critical section statement. Stefan
On 08/12/2011 02:45 PM, Stefan Behnel wrote:
[second try in moving this discussion to cython-devel]
Dag Sverre Seljebotn, 12.08.2011 08:50:
On 08/12/2011 06:44 AM, Robert Bradshaw wrote:
On Thu, Aug 11, 2011 at 5:53 AM, Dag Sverre Seljebotn <d.s.seljebotn@astro.uio.no> wrote:
Are you still against this mini-CEP?:
with cython.global_lock(): ...
Where global_lock() is GIL-requiring noop.
Just reading this, it's not immediately obvious what this means. (I thought at first this was different syntax for "with gil"...)
True. "cython.synchronized"? The synchronized keyword in Java does not quite the same thing but almost.
This
a) Improves code readability vastly. Having a critical section take effect because of the *lack* of a keyword is just very odd to anyone who's not shoulder deep in CPython internals
I'm not following you here. The only way to run into this is if you have explicitly release it. Presumably you can learn both keywords at the same time. Perhaps extern function could be nogil by default.
I'll try to explain again. Consider code like this:
cdef call_c(): magic_c_function(3)
This code is perfectly fine even if magic_c_function is not reentrant -- but that's hardly well documented! So it's conceivable that another programmer comes along (who doesn't know the C library well) and decides that "somebody has just been too lazy to add the nogil specifier" and slaps it on -- at which point you have a bug.
This is more to the point in creating readable code IMO:
cdef call_c(): with cython.synchronized(): magic_c_function(3)
I think I'm as confused as Robert here. Is that the GIL or some separate lock?
If the latter, where would that lock be stored? Module-wide? While there are certainly use cases for that, I think it's much more common to either a) use the GIL or b) use an explicit lock at some well defined point, e.g. at an object or class level.
I intended it to be the GIL in current CPython. In GIL-less environments (whether Java, .NET or some future CPython) one would manuall ensure a fully global lock (inserting a _cython module in sys.path etc.). But:
I don't think we disagree when I say that locking should be explicit, but that includes the "thing" that keeps the lock during its lifetime.
Also, consider your classical race conditions:
cdef init(): global resource if resource == NULL: resource = malloc(sizeof(resource_t)) ...
This is safe code.
Well, it's safe code as long as there is no Python code interaction in between. Calling back into the interpreter may trigger a thread switch.
Admittedly, this is not obvious and tends to introduce bugs. I learned that the hard way in lxml, actually twice.
If your "synchronised" directive refers to the GIL, then it would suffer from that problem as well. I think that's very undesirable for an explicit critical section statement.
This is a good point. Hmm. This all started with your comment "Even a trivial function may require an exclusive global lock for some reason, and it's common to use the GIL for that. So the programmer must be explicit here." And my problem is that it's too implicit -- when you /require/ the global lock, you /leave out/ the nogil modifier. I just wanted to find some way about being explicit about what you already do. So it may be a question of naming. As you mention, using the GIL has drawbacks, but it performs better than a seperate lock when you know there won't be callbacks into Python... Dag Sverre
On Fri, Aug 12, 2011 at 6:13 AM, Dag Sverre Seljebotn <d.s.seljebotn@astro.uio.no> wrote:
On 08/12/2011 02:45 PM, Stefan Behnel wrote:
[second try in moving this discussion to cython-devel]
Dag Sverre Seljebotn, 12.08.2011 08:50:
On 08/12/2011 06:44 AM, Robert Bradshaw wrote:
On Thu, Aug 11, 2011 at 5:53 AM, Dag Sverre Seljebotn <d.s.seljebotn@astro.uio.no> wrote:
Are you still against this mini-CEP?:
with cython.global_lock(): ...
Where global_lock() is GIL-requiring noop.
Just reading this, it's not immediately obvious what this means. (I thought at first this was different syntax for "with gil"...)
True. "cython.synchronized"? The synchronized keyword in Java does not quite the same thing but almost.
This
a) Improves code readability vastly. Having a critical section take effect because of the *lack* of a keyword is just very odd to anyone who's not shoulder deep in CPython internals
I'm not following you here. The only way to run into this is if you have explicitly release it. Presumably you can learn both keywords at the same time. Perhaps extern function could be nogil by default.
I'll try to explain again. Consider code like this:
cdef call_c(): magic_c_function(3)
This code is perfectly fine even if magic_c_function is not reentrant -- but that's hardly well documented! So it's conceivable that another programmer comes along (who doesn't know the C library well) and decides that "somebody has just been too lazy to add the nogil specifier" and slaps it on -- at which point you have a bug.
This is more to the point in creating readable code IMO:
cdef call_c(): with cython.synchronized(): magic_c_function(3)
I think I'm as confused as Robert here. Is that the GIL or some separate lock?
If the latter, where would that lock be stored? Module-wide? While there are certainly use cases for that, I think it's much more common to either a) use the GIL or b) use an explicit lock at some well defined point, e.g. at an object or class level.
I intended it to be the GIL in current CPython. In GIL-less environments (whether Java, .NET or some future CPython) one would manuall ensure a fully global lock (inserting a _cython module in sys.path etc.).
But:
I don't think we disagree when I say that locking should be explicit, but that includes the "thing" that keeps the lock during its lifetime.
Also, consider your classical race conditions:
cdef init(): global resource if resource == NULL: resource = malloc(sizeof(resource_t)) ...
This is safe code.
Well, it's safe code as long as there is no Python code interaction in between. Calling back into the interpreter may trigger a thread switch.
Admittedly, this is not obvious and tends to introduce bugs. I learned that the hard way in lxml, actually twice.
If your "synchronised" directive refers to the GIL, then it would suffer from that problem as well. I think that's very undesirable for an explicit critical section statement.
This is a good point.
Hmm. This all started with your comment "Even a trivial function may require an exclusive global lock for some reason, and it's common to use the GIL for that. So the programmer must be explicit here."
And my problem is that it's too implicit -- when you /require/ the global lock, you /leave out/ the nogil modifier.
That's a good point.
I just wanted to find some way about being explicit about what you already do. So it may be a question of naming. As you mention, using the GIL has drawbacks, but it performs better than a seperate lock when you know there won't be callbacks into Python...
So your proposal is that "with cython.synchronized" has the same effect as a Python operation, in that its a compile time error to do it while not holding the gil? (As opposed to "with gil" which actively acquires the lock (which is more similar to java synchronized)?) Would this cause the function to have a GIL requiring/acquiring signature? I suppose the reason that one implicitly holds the gil is that it allows you to do arbitrary Python operations by default. Having to explicitly mark when one wants to hold the GIL would be a big regression for applications that do a lot of Python interaction (e.g. wrappers). I'm still thinking it could be reasonable for extern functions to be nogil by default, as a user of C libraries is expected to manually and externally respect its threading constraints. (This would require a long deprecation period.) - Robert
On 08/17/2011 09:12 AM, Robert Bradshaw wrote:
On Fri, Aug 12, 2011 at 6:13 AM, Dag Sverre Seljebotn <d.s.seljebotn@astro.uio.no> wrote:
On 08/12/2011 02:45 PM, Stefan Behnel wrote:
[second try in moving this discussion to cython-devel]
Dag Sverre Seljebotn, 12.08.2011 08:50:
On 08/12/2011 06:44 AM, Robert Bradshaw wrote:
On Thu, Aug 11, 2011 at 5:53 AM, Dag Sverre Seljebotn <d.s.seljebotn@astro.uio.no> wrote:
Are you still against this mini-CEP?:
with cython.global_lock(): ...
Where global_lock() is GIL-requiring noop.
Just reading this, it's not immediately obvious what this means. (I thought at first this was different syntax for "with gil"...)
True. "cython.synchronized"? The synchronized keyword in Java does not quite the same thing but almost.
This
a) Improves code readability vastly. Having a critical section take effect because of the *lack* of a keyword is just very odd to anyone who's not shoulder deep in CPython internals
I'm not following you here. The only way to run into this is if you have explicitly release it. Presumably you can learn both keywords at the same time. Perhaps extern function could be nogil by default.
I'll try to explain again. Consider code like this:
cdef call_c(): magic_c_function(3)
This code is perfectly fine even if magic_c_function is not reentrant -- but that's hardly well documented! So it's conceivable that another programmer comes along (who doesn't know the C library well) and decides that "somebody has just been too lazy to add the nogil specifier" and slaps it on -- at which point you have a bug.
This is more to the point in creating readable code IMO:
cdef call_c(): with cython.synchronized(): magic_c_function(3)
I think I'm as confused as Robert here. Is that the GIL or some separate lock?
If the latter, where would that lock be stored? Module-wide? While there are certainly use cases for that, I think it's much more common to either a) use the GIL or b) use an explicit lock at some well defined point, e.g. at an object or class level.
I intended it to be the GIL in current CPython. In GIL-less environments (whether Java, .NET or some future CPython) one would manuall ensure a fully global lock (inserting a _cython module in sys.path etc.).
But:
I don't think we disagree when I say that locking should be explicit, but that includes the "thing" that keeps the lock during its lifetime.
Also, consider your classical race conditions:
cdef init(): global resource if resource == NULL: resource = malloc(sizeof(resource_t)) ...
This is safe code.
Well, it's safe code as long as there is no Python code interaction in between. Calling back into the interpreter may trigger a thread switch.
Admittedly, this is not obvious and tends to introduce bugs. I learned that the hard way in lxml, actually twice.
If your "synchronised" directive refers to the GIL, then it would suffer from that problem as well. I think that's very undesirable for an explicit critical section statement.
This is a good point.
Hmm. This all started with your comment "Even a trivial function may require an exclusive global lock for some reason, and it's common to use the GIL for that. So the programmer must be explicit here."
And my problem is that it's too implicit -- when you /require/ the global lock, you /leave out/ the nogil modifier.
That's a good point.
I just wanted to find some way about being explicit about what you already do. So it may be a question of naming. As you mention, using the GIL has drawbacks, but it performs better than a seperate lock when you know there won't be callbacks into Python...
So your proposal is that "with cython.synchronized" has the same effect as a Python operation, in that its a compile time error to do it while not holding the gil? (As opposed to "with gil" which actively acquires the lock (which is more similar to java synchronized)?) Would
Yes, the former. It does not acquire a lock under curreent CPython. But the intention is very much to prepare the ground for IronPython/Jython/GIL-less CPython/autogil-in-Cython too. Basically a tool to protect & document logic that depends on GIL to avoid races, so that it is future-safe. So in Cython-for-Jython it would have to acquire a lock, and be more like Java synchronized.
this cause the function to have a GIL requiring/acquiring signature? I
Not in isolation. But, IF (after a long deprecation cycle) we start to infer "nogil" on function signatures, then the presence of this Python statement would stop nogil from getting inferred. The intention is simply: If you have a cdef function which uses no Python operations, but still relies on holding the GIL to avoid race conditions (exactly the situation Stefan described initially), then you can use cython.synchronized to avoid any future inference from removing the GIL.
suppose the reason that one implicitly holds the gil is that it allows you to do arbitrary Python operations by default. Having to explicitly mark when one wants to hold the GIL would be a big regression for applications that do a lot of Python interaction (e.g. wrappers).
Yes, I'm not proposing that at all.
I'm still thinking it could be reasonable for extern functions to be nogil by default, as a user of C libraries is expected to manually and externally respect its threading constraints. (This would require a long deprecation period.)
+1. Perhaps this would be safer if we introduce "expects gil" (explicit declaration for neither "nogil" or "with gil"), and then start to emit warnings if a GIL-mode isn't declared on cdef functions which has their address taken. Thus, if you pass a callback to a C library, you'll get a reminder to declare a GIL mode. Dag Sverre
On Wed, Aug 17, 2011 at 1:08 AM, Dag Sverre Seljebotn <d.s.seljebotn@astro.uio.no> wrote:
On 08/17/2011 09:12 AM, Robert Bradshaw wrote:
So your proposal is that "with cython.synchronized" has the same effect as a Python operation, in that its a compile time error to do it while not holding the gil? (As opposed to "with gil" which actively acquires the lock (which is more similar to java synchronized)?) Would
Yes, the former. It does not acquire a lock under curreent CPython.
But the intention is very much to prepare the ground for IronPython/Jython/GIL-less CPython/autogil-in-Cython too. Basically a tool to protect & document logic that depends on GIL to avoid races, so that it is future-safe.
So in Cython-for-Jython it would have to acquire a lock, and be more like Java synchronized.
I think a with gil statement (always acquiring the lock) has more consistent semantics and accomplishes the same goal. Is "with gil" expensive if one already has the gil? I'm assuming here that the gil is re-entrant (or could be made to see so).
this cause the function to have a GIL requiring/acquiring signature? I
Not in isolation.
But, IF (after a long deprecation cycle) we start to infer "nogil" on function signatures, then the presence of this Python statement would stop nogil from getting inferred.
Knowing the subtleties of whether any Python operations are used, especially as the specific optimizations done continue to evolve, this seems like a dangerous thing to infer.
The intention is simply: If you have a cdef function which uses no Python operations, but still relies on holding the GIL to avoid race conditions (exactly the situation Stefan described initially), then you can use cython.synchronized to avoid any future inference from removing the GIL.
Again, with gil, if acceptable from a gil-holding context, seems sufficient. Then if one did such inference, one could isolate it to the important block.
suppose the reason that one implicitly holds the gil is that it allows you to do arbitrary Python operations by default. Having to explicitly mark when one wants to hold the GIL would be a big regression for applications that do a lot of Python interaction (e.g. wrappers).
Yes, I'm not proposing that at all.
I'm still thinking it could be reasonable for extern functions to be nogil by default, as a user of C libraries is expected to manually and externally respect its threading constraints. (This would require a long deprecation period.)
+1.
Actually, it's relatively safe to switch, as it will only make currently illegal code legal, but won't break existing code.
Perhaps this would be safer if we introduce "expects gil" (explicit declaration for neither "nogil" or "with gil"), and then start to emit warnings if a GIL-mode isn't declared on cdef functions which has their address taken.
Thus, if you pass a callback to a C library, you'll get a reminder to declare a GIL mode.
That's a nice idea. I have to admit that all these special gil declarations are a bit messy. I'd also rather introduce clear decorators, e.g. @cython.requires_gil # expects gil cdef a(): ... @cython.requires.gil(False) # nogil cdef b(): ... @cython.aquires_gil # with gil cdef c(): ... (Actually, now that we have the "with gil" statement, it could be worth considering simply noticing the pattern of the entire function body in a with gil block/as the first statement and acquiring the GIL before argument parsing.) Note that we need to declare functions as requiring the GIL to allow for declaring cpython.pxd if extern functions are implicitly nogil. - Robert
On 08/17/2011 08:19 PM, Robert Bradshaw wrote:
That's a nice idea. I have to admit that all these special gil declarations are a bit messy. I'd also rather introduce clear decorators, e.g.
@cython.requires_gil # expects gil cdef a(): ...
@cython.requires.gil(False) # nogil cdef b(): ...
@cython.aquires_gil # with gil cdef c(): ...
(Actually, now that we have the "with gil" statement, it could be worth considering simply noticing the pattern of the entire function body in a with gil block/as the first statement and acquiring the GIL before argument parsing.)
Note that we need to declare functions as requiring the GIL to allow for declaring cpython.pxd if extern functions are implicitly nogil.
I agree, it's messy in the current situation, simplifying would be good. Assuming we can't acquire the GIL in every single function just to be sure, I have a hunch that the "acquires_gil" aspect of a function is just declared in the wrong place. I mean, the same function might be passed as a callback to C both while holding the GIL and while not holding the GIL -- it would be nice to automatically wrap it in a GIL-acquiring wrapper only when needed. So to me it makes more sense to have acquires_gil be part of function pointer types, or of the C call where the pointer is passed, or similar. Sort of like an FFI. Can't think of a practical scheme that's more user-friendly than the current way though... Dag Sverre
On Wed, Aug 17, 2011 at 11:46 AM, Dag Sverre Seljebotn <d.s.seljebotn@astro.uio.no> wrote:
On 08/17/2011 08:19 PM, Robert Bradshaw wrote:
That's a nice idea. I have to admit that all these special gil declarations are a bit messy. I'd also rather introduce clear decorators, e.g.
@cython.requires_gil # expects gil cdef a(): ...
@cython.requires.gil(False) # nogil cdef b(): ...
@cython.aquires_gil # with gil cdef c(): ...
(Actually, now that we have the "with gil" statement, it could be worth considering simply noticing the pattern of the entire function body in a with gil block/as the first statement and acquiring the GIL before argument parsing.)
Note that we need to declare functions as requiring the GIL to allow for declaring cpython.pxd if extern functions are implicitly nogil.
I agree, it's messy in the current situation, simplifying would be good.
Assuming we can't acquire the GIL in every single function just to be sure, I have a hunch that the "acquires_gil" aspect of a function is just declared in the wrong place. I mean, the same function might be passed as a callback to C both while holding the GIL and while not holding the GIL -- it would be nice to automatically wrap it in a GIL-acquiring wrapper only when needed.
So to me it makes more sense to have acquires_gil be part of function pointer types, or of the C call where the pointer is passed, or similar. Sort of like an FFI. Can't think of a practical scheme that's more user-friendly than the current way though...
I was thinking the opposite, "aquires_gil" should be completely transparent to the caller (assuming it's cheap enough to check-or-acquire, but that's an optimization not API issue). On the other hand requires/does not require does need to be visible to the caller though, which argues for it being part of the signature. Regarding inference, are you thinking the semantics being that we (re)-acquire the GIL for every individual operation that needs it (including python operations or entire with gil blocks), with the obvious optimization that we may choose to not release it between (nearly) consecutive blocks of code that all need the GIL? That would be truer to Python semantics, but would require risky guesswork at compile time or some kind of periodic runtime checks. (It would also be a strongly backwards incompatible move, so as mentioned you'd need some kind of a explicit marker and deprecation period.) - Robert
On 08/17/2011 09:21 PM, Robert Bradshaw wrote:
On Wed, Aug 17, 2011 at 11:46 AM, Dag Sverre Seljebotn <d.s.seljebotn@astro.uio.no> wrote:
On 08/17/2011 08:19 PM, Robert Bradshaw wrote:
That's a nice idea. I have to admit that all these special gil declarations are a bit messy. I'd also rather introduce clear decorators, e.g.
@cython.requires_gil # expects gil cdef a(): ...
@cython.requires.gil(False) # nogil cdef b(): ...
@cython.aquires_gil # with gil cdef c(): ...
(Actually, now that we have the "with gil" statement, it could be worth considering simply noticing the pattern of the entire function body in a with gil block/as the first statement and acquiring the GIL before argument parsing.)
Note that we need to declare functions as requiring the GIL to allow for declaring cpython.pxd if extern functions are implicitly nogil.
I agree, it's messy in the current situation, simplifying would be good.
Assuming we can't acquire the GIL in every single function just to be sure, I have a hunch that the "acquires_gil" aspect of a function is just declared in the wrong place. I mean, the same function might be passed as a callback to C both while holding the GIL and while not holding the GIL -- it would be nice to automatically wrap it in a GIL-acquiring wrapper only when needed.
So to me it makes more sense to have acquires_gil be part of function pointer types, or of the C call where the pointer is passed, or similar. Sort of like an FFI. Can't think of a practical scheme that's more user-friendly than the current way though...
I was thinking the opposite, "aquires_gil" should be completely transparent to the caller (assuming it's cheap enough to check-or-acquire, but that's an optimization not API issue). On the other hand requires/does not require does need to be visible to the caller though, which argues for it being part of the signature.
Are you saying that every single function cdef function, ever, that are not "nogil" should have acqusition semantics? Those semantics would be great, but I worry a bit about performance -- we just agreed to make function GIL-acquisition even a bit more expensive with that check... Hmm. How about this: i) Every cdef function that needs the GIL to be held generates a GIL-acquiring wrapper function as well. ii) Whenever taking the address of such a function, you get the address of the GIL-requiring wrapper, which can safely be used from any code, whether holding the GIL or not. iii) However, Cython code that already holds the GIL can call the inner function directly, as an optimization. Should be possible to do this across pxd's as well. iv) We may introduce a cython.nogil_function_address or similar just to provide an option to get around ii). v) The "with gil" on functions simply ceases to take effect, and is deprecated from the language.
Regarding inference, are you thinking the semantics being that we (re)-acquire the GIL for every individual operation that needs it (including python operations or entire with gil blocks), with the obvious optimization that we may choose to not release it between (nearly) consecutive blocks of code that all need the GIL? That would be truer to Python semantics, but would require risky guesswork at compile time or some kind of periodic runtime checks. (It would also be a strongly backwards incompatible move, so as mentioned you'd need some kind of a explicit marker and deprecation period.)
No, I wasn't talking about this at all (this time on the list -- I did mention that I wished for this behaviour in Munich, but that's really long term). All I wished for now was for simple code like this: cdef double f(double x): return x**2 + x to be callable without holding the GIL. In particular since this is the major reason why prange users need to learn the "nogil" keyword. The semantics are simple: For all cdef functions, if "nogil" could have been applied without a syntax error, then it gets automatically applied. The only time this isn't completely safe is when the GIL is intentionally being used as a lock. Dag Sverre
On 08/18/2011 08:39 AM, Dag Sverre Seljebotn wrote:
On 08/17/2011 09:21 PM, Robert Bradshaw wrote:
On Wed, Aug 17, 2011 at 11:46 AM, Dag Sverre Seljebotn <d.s.seljebotn@astro.uio.no> wrote:
On 08/17/2011 08:19 PM, Robert Bradshaw wrote:
That's a nice idea. I have to admit that all these special gil declarations are a bit messy. I'd also rather introduce clear decorators, e.g.
@cython.requires_gil # expects gil cdef a(): ...
@cython.requires.gil(False) # nogil cdef b(): ...
@cython.aquires_gil # with gil cdef c(): ...
(Actually, now that we have the "with gil" statement, it could be worth considering simply noticing the pattern of the entire function body in a with gil block/as the first statement and acquiring the GIL before argument parsing.)
Note that we need to declare functions as requiring the GIL to allow for declaring cpython.pxd if extern functions are implicitly nogil.
I agree, it's messy in the current situation, simplifying would be good.
Assuming we can't acquire the GIL in every single function just to be sure, I have a hunch that the "acquires_gil" aspect of a function is just declared in the wrong place. I mean, the same function might be passed as a callback to C both while holding the GIL and while not holding the GIL -- it would be nice to automatically wrap it in a GIL-acquiring wrapper only when needed.
So to me it makes more sense to have acquires_gil be part of function pointer types, or of the C call where the pointer is passed, or similar. Sort of like an FFI. Can't think of a practical scheme that's more user-friendly than the current way though...
I was thinking the opposite, "aquires_gil" should be completely transparent to the caller (assuming it's cheap enough to check-or-acquire, but that's an optimization not API issue). On the other hand requires/does not require does need to be visible to the caller though, which argues for it being part of the signature.
Are you saying that every single function cdef function, ever, that are not "nogil" should have acqusition semantics?
Those semantics would be great, but I worry a bit about performance -- we just agreed to make function GIL-acquisition even a bit more expensive with that check...
Hmm. How about this:
i) Every cdef function that needs the GIL to be held generates a GIL-acquiring wrapper function as well.
ii) Whenever taking the address of such a function, you get the address of the GIL-requiring wrapper, which can safely be used from any code, whether holding the GIL or not.
iii) However, Cython code that already holds the GIL can call the inner function directly, as an optimization. Should be possible to do this across pxd's as well.
iv) We may introduce a cython.nogil_function_address or similar just to provide an option to get around ii).
v) The "with gil" on functions simply ceases to take effect, and is deprecated from the language.
Relevant benchmarks on my laptop: Calling an almost-noop cdef function (in a loop): 0.7 ns per call Calling same function with "with gil": 58 ns per call A dict lookup + Python integer-object addition: 57 ns per iteration I think the cost (basically 2 python ops) is too high to go for the simpler scheme of simply making everything "with gil" that is not "nogil"? Also, the GIL-initialization check will make it even more expensive. cdef int noop(int i) nogil: return 2 * i cdef int withgil(int i) with gil: return 2 * i def call_noop(int reps): cdef int i cdef int s = 0 for i in range(reps): s += noop(i) return s def call_withgil(int reps): cdef int i cdef int s = 0 for i in range(reps): s += withgil(i) return s def call_dict(int reps): cdef int i cdef object s = 0 for i in range(reps): s += d['2'] return s d = {} for i in range(15): d[str(i)] = i Dag SVerre
Dag Sverre Seljebotn, 18.08.2011 08:39:
The semantics are simple: For all cdef functions, if "nogil" could have been applied without a syntax error, then it gets automatically applied.
The only time this isn't completely safe is when the GIL is intentionally being used as a lock.
In which case, IMHO, it's actually a good idea to require an explicit declaration, because it makes this intention explicitly visible in the source code. I take it that auto-nogil semantics for a function wouldn't automatically *release* the GIL. They'd just not require it, right? So all that would change is that you wouldn't get a compiler error when calling such a function without holding the GIL. That shouldn't break all that much code... Stefan
On 08/18/2011 09:06 AM, Stefan Behnel wrote:
Dag Sverre Seljebotn, 18.08.2011 08:39:
The semantics are simple: For all cdef functions, if "nogil" could have been applied without a syntax error, then it gets automatically applied.
The only time this isn't completely safe is when the GIL is intentionally being used as a lock.
In which case, IMHO, it's actually a good idea to require an explicit declaration, because it makes this intention explicitly visible in the source code.
I take it that auto-nogil semantics for a function wouldn't automatically *release* the GIL. They'd just not require it, right? So
Right. Sorry about not making it clearer earlier.
all that would change is that you wouldn't get a compiler error when calling such a function without holding the GIL.
That shouldn't break all that much code...
Happy that we agree! Dag Sverre
On Wed, Aug 17, 2011 at 11:39 PM, Dag Sverre Seljebotn <d.s.seljebotn@astro.uio.no> wrote:
On 08/17/2011 09:21 PM, Robert Bradshaw wrote:
On Wed, Aug 17, 2011 at 11:46 AM, Dag Sverre Seljebotn <d.s.seljebotn@astro.uio.no> wrote:
On 08/17/2011 08:19 PM, Robert Bradshaw wrote:
That's a nice idea. I have to admit that all these special gil declarations are a bit messy. I'd also rather introduce clear decorators, e.g.
@cython.requires_gil # expects gil cdef a(): ...
@cython.requires.gil(False) # nogil cdef b(): ...
@cython.aquires_gil # with gil cdef c(): ...
(Actually, now that we have the "with gil" statement, it could be worth considering simply noticing the pattern of the entire function body in a with gil block/as the first statement and acquiring the GIL before argument parsing.)
Note that we need to declare functions as requiring the GIL to allow for declaring cpython.pxd if extern functions are implicitly nogil.
I agree, it's messy in the current situation, simplifying would be good.
Assuming we can't acquire the GIL in every single function just to be sure, I have a hunch that the "acquires_gil" aspect of a function is just declared in the wrong place. I mean, the same function might be passed as a callback to C both while holding the GIL and while not holding the GIL -- it would be nice to automatically wrap it in a GIL-acquiring wrapper only when needed.
So to me it makes more sense to have acquires_gil be part of function pointer types, or of the C call where the pointer is passed, or similar. Sort of like an FFI. Can't think of a practical scheme that's more user-friendly than the current way though...
I was thinking the opposite, "aquires_gil" should be completely transparent to the caller (assuming it's cheap enough to check-or-acquire, but that's an optimization not API issue). On the other hand requires/does not require does need to be visible to the caller though, which argues for it being part of the signature.
Are you saying that every single function cdef function, ever, that are not "nogil" should have acqusition semantics?
No, I was saying that the distinction between with gil and nogil should be transparent (semantically) to the caller.
Those semantics would be great, but I worry a bit about performance -- we just agreed to make function GIL-acquisition even a bit more expensive with that check...
According to your timings, the performance argument is a good one.
Hmm. How about this:
i) Every cdef function that needs the GIL to be held generates a GIL-acquiring wrapper function as well.
ii) Whenever taking the address of such a function, you get the address of the GIL-requiring wrapper, which can safely be used from any code, whether holding the GIL or not.
You mean GIL-acquiring wrapper, right?
iii) However, Cython code that already holds the GIL can call the inner function directly, as an optimization. Should be possible to do this across pxd's as well.
iv) We may introduce a cython.nogil_function_address or similar just to provide an option to get around ii).
v) The "with gil" on functions simply ceases to take effect, and is deprecated from the language.
Regarding inference, are you thinking the semantics being that we (re)-acquire the GIL for every individual operation that needs it (including python operations or entire with gil blocks), with the obvious optimization that we may choose to not release it between (nearly) consecutive blocks of code that all need the GIL? That would be truer to Python semantics, but would require risky guesswork at compile time or some kind of periodic runtime checks. (It would also be a strongly backwards incompatible move, so as mentioned you'd need some kind of a explicit marker and deprecation period.)
No, I wasn't talking about this at all (this time on the list -- I did mention that I wished for this behaviour in Munich, but that's really long term).
All I wished for now was for simple code like this:
cdef double f(double x): return x**2 + x
to be callable without holding the GIL. In particular since this is the major reason why prange users need to learn the "nogil" keyword.
The semantics are simple: For all cdef functions, if "nogil" could have been applied without a syntax error, then it gets automatically applied.
Give that the implicit nogil marker is a function of the function's body, how would this information be propagated across pxd files? Perhaps I'm confused, we have cdef double f(double x): # implicitly nogil return x**2 + x cdef double f(double x): # implicitly "with gil" or implicitly "requires gil"? print x return x**2 + x If "with gil" then constant, implicit gil acquisition could be a non-obvious performance hit; if "requires gil" then I don't see how to propagate accross .pxd files. (I do like the direction this is heading, just pointing out some cons.)
The only time this isn't completely safe is when the GIL is intentionally being used as a lock.
Or unintentionally being used as a lock... (Yes, that'd be user error.) The idea that adding a print statement to a function's body can produce such a large change is somewhat worrisome, but perhaps worth it. - Robert
On Thu, Aug 18, 2011 at 12:27 PM, Robert Bradshaw <robertwb@math.washington.edu> wrote:
On Wed, Aug 17, 2011 at 11:39 PM, Dag Sverre Seljebotn <d.s.seljebotn@astro.uio.no> wrote:
On 08/17/2011 09:21 PM, Robert Bradshaw wrote:
On Wed, Aug 17, 2011 at 11:46 AM, Dag Sverre Seljebotn <d.s.seljebotn@astro.uio.no> wrote:
On 08/17/2011 08:19 PM, Robert Bradshaw wrote:
That's a nice idea. I have to admit that all these special gil declarations are a bit messy. I'd also rather introduce clear decorators, e.g.
@cython.requires_gil # expects gil cdef a(): ...
@cython.requires.gil(False) # nogil cdef b(): ...
@cython.aquires_gil # with gil cdef c(): ...
(Actually, now that we have the "with gil" statement, it could be worth considering simply noticing the pattern of the entire function body in a with gil block/as the first statement and acquiring the GIL before argument parsing.)
Note that we need to declare functions as requiring the GIL to allow for declaring cpython.pxd if extern functions are implicitly nogil.
I agree, it's messy in the current situation, simplifying would be good.
Assuming we can't acquire the GIL in every single function just to be sure, I have a hunch that the "acquires_gil" aspect of a function is just declared in the wrong place. I mean, the same function might be passed as a callback to C both while holding the GIL and while not holding the GIL -- it would be nice to automatically wrap it in a GIL-acquiring wrapper only when needed.
So to me it makes more sense to have acquires_gil be part of function pointer types, or of the C call where the pointer is passed, or similar. Sort of like an FFI. Can't think of a practical scheme that's more user-friendly than the current way though...
I was thinking the opposite, "aquires_gil" should be completely transparent to the caller (assuming it's cheap enough to check-or-acquire, but that's an optimization not API issue). On the other hand requires/does not require does need to be visible to the caller though, which argues for it being part of the signature.
Are you saying that every single function cdef function, ever, that are not "nogil" should have acqusition semantics?
No, I was saying that the distinction between with gil and nogil should be transparent (semantically) to the caller.
Those semantics would be great, but I worry a bit about performance -- we just agreed to make function GIL-acquisition even a bit more expensive with that check...
According to your timings, the performance argument is a good one.
Hmm. How about this:
i) Every cdef function that needs the GIL to be held generates a GIL-acquiring wrapper function as well.
ii) Whenever taking the address of such a function, you get the address of the GIL-requiring wrapper, which can safely be used from any code, whether holding the GIL or not.
You mean GIL-acquiring wrapper, right?
iii) However, Cython code that already holds the GIL can call the inner function directly, as an optimization. Should be possible to do this across pxd's as well.
iv) We may introduce a cython.nogil_function_address or similar just to provide an option to get around ii).
v) The "with gil" on functions simply ceases to take effect, and is deprecated from the language.
Regarding inference, are you thinking the semantics being that we (re)-acquire the GIL for every individual operation that needs it (including python operations or entire with gil blocks), with the obvious optimization that we may choose to not release it between (nearly) consecutive blocks of code that all need the GIL? That would be truer to Python semantics, but would require risky guesswork at compile time or some kind of periodic runtime checks. (It would also be a strongly backwards incompatible move, so as mentioned you'd need some kind of a explicit marker and deprecation period.)
No, I wasn't talking about this at all (this time on the list -- I did mention that I wished for this behaviour in Munich, but that's really long term).
All I wished for now was for simple code like this:
cdef double f(double x): return x**2 + x
to be callable without holding the GIL. In particular since this is the major reason why prange users need to learn the "nogil" keyword.
The semantics are simple: For all cdef functions, if "nogil" could have been applied without a syntax error, then it gets automatically applied.
Give that the implicit nogil marker is a function of the function's body, how would this information be propagated across pxd files? Perhaps I'm confused, we have
cdef double f(double x): # implicitly nogil return x**2 + x
cdef double f(double x): # implicitly "with gil" or implicitly "requires gil"? print x return x**2 + x
If "with gil" then constant, implicit gil acquisition could be a non-obvious performance hit; if "requires gil" then I don't see how to propagate accross .pxd files. (I do like the direction this is heading, just pointing out some cons.)
On second though, "with gil" (= "acquires gil") isn't that bad, because the mantra of "look for unneeded Python operations" to speed up your code directly applies here, and acquiring the GIL is about as expensive as the one or two operations that requested it.
The only time this isn't completely safe is when the GIL is intentionally being used as a lock.
Or unintentionally being used as a lock... (Yes, that'd be user error.) The idea that adding a print statement to a function's body can produce such a large change is somewhat worrisome, but perhaps worth it.
- Robert
On 08/18/2011 09:27 PM, Robert Bradshaw wrote:
On Wed, Aug 17, 2011 at 11:39 PM, Dag Sverre Seljebotn <d.s.seljebotn@astro.uio.no> wrote:
On 08/17/2011 09:21 PM, Robert Bradshaw wrote:
On Wed, Aug 17, 2011 at 11:46 AM, Dag Sverre Seljebotn <d.s.seljebotn@astro.uio.no> wrote:
On 08/17/2011 08:19 PM, Robert Bradshaw wrote:
That's a nice idea. I have to admit that all these special gil declarations are a bit messy. I'd also rather introduce clear decorators, e.g.
@cython.requires_gil # expects gil cdef a(): ...
@cython.requires.gil(False) # nogil cdef b(): ...
@cython.aquires_gil # with gil cdef c(): ...
(Actually, now that we have the "with gil" statement, it could be worth considering simply noticing the pattern of the entire function body in a with gil block/as the first statement and acquiring the GIL before argument parsing.)
Note that we need to declare functions as requiring the GIL to allow for declaring cpython.pxd if extern functions are implicitly nogil.
I agree, it's messy in the current situation, simplifying would be good.
Assuming we can't acquire the GIL in every single function just to be sure, I have a hunch that the "acquires_gil" aspect of a function is just declared in the wrong place. I mean, the same function might be passed as a callback to C both while holding the GIL and while not holding the GIL -- it would be nice to automatically wrap it in a GIL-acquiring wrapper only when needed.
So to me it makes more sense to have acquires_gil be part of function pointer types, or of the C call where the pointer is passed, or similar. Sort of like an FFI. Can't think of a practical scheme that's more user-friendly than the current way though...
I was thinking the opposite, "aquires_gil" should be completely transparent to the caller (assuming it's cheap enough to check-or-acquire, but that's an optimization not API issue). On the other hand requires/does not require does need to be visible to the caller though, which argues for it being part of the signature.
Are you saying that every single function cdef function, ever, that are not "nogil" should have acqusition semantics?
No, I was saying that the distinction between with gil and nogil should be transparent (semantically) to the caller.
Those semantics would be great, but I worry a bit about performance -- we just agreed to make function GIL-acquisition even a bit more expensive with that check...
According to your timings, the performance argument is a good one.
Hmm. How about this:
i) Every cdef function that needs the GIL to be held generates a GIL-acquiring wrapper function as well.
ii) Whenever taking the address of such a function, you get the address of the GIL-requiring wrapper, which can safely be used from any code, whether holding the GIL or not.
You mean GIL-acquiring wrapper, right?
Yes, sorry.
iii) However, Cython code that already holds the GIL can call the inner function directly, as an optimization. Should be possible to do this across pxd's as well.
iv) We may introduce a cython.nogil_function_address or similar just to provide an option to get around ii).
v) The "with gil" on functions simply ceases to take effect, and is deprecated from the language.
Regarding inference, are you thinking the semantics being that we (re)-acquire the GIL for every individual operation that needs it (including python operations or entire with gil blocks), with the obvious optimization that we may choose to not release it between (nearly) consecutive blocks of code that all need the GIL? That would be truer to Python semantics, but would require risky guesswork at compile time or some kind of periodic runtime checks. (It would also be a strongly backwards incompatible move, so as mentioned you'd need some kind of a explicit marker and deprecation period.)
No, I wasn't talking about this at all (this time on the list -- I did mention that I wished for this behaviour in Munich, but that's really long term).
All I wished for now was for simple code like this:
cdef double f(double x): return x**2 + x
to be callable without holding the GIL. In particular since this is the major reason why prange users need to learn the "nogil" keyword.
The semantics are simple: For all cdef functions, if "nogil" could have been applied without a syntax error, then it gets automatically applied.
Give that the implicit nogil marker is a function of the function's body, how would this information be propagated across pxd files? Perhaps I'm confused, we have
cdef double f(double x): # implicitly nogil return x**2 + x
cdef double f(double x): # implicitly "with gil" or implicitly "requires gil"? print x return x**2 + x
If "with gil" then constant, implicit gil acquisition could be a non-obvious performance hit; if "requires gil" then I don't see how to propagate accross .pxd files. (I do like the direction this is heading, just pointing out some cons.)
True, I didn't think about the pxd issue. Brainstorming: I) Downsize my proposal to within-module calls, require nogil for cross-module. II) Change Cython so that any function can be called from within "nogil" sections (and then their GIL-acquiring wrapper, if any, will be called). Of course this is a little fussy regarding exceptions etc. and need some thinking through (which I haven't done). Together with the proposal above to deprecate the "with gil" modifier and always generate GIL-acquiring wrappers, this works across modules: The module function pointer table gets two slots per cdef function; one to call if the GIL is held, and one to call if the GIL is not held. Functions that are nogil (explicitly or implicitly) then simply use the same pointer in both slots.
The only time this isn't completely safe is when the GIL is intentionally being used as a lock.
Or unintentionally being used as a lock... (Yes, that'd be user error.) The idea that adding a print statement to a function's body can produce such a large change is somewhat worrisome, but perhaps worth it.
My hunch is to postpone the question of inferring the nogil modifier. Instead, first focus on making the "with gil" modifier optional (GIL-acquiring wrapper on all cdef functions), and see where that takes us. I guess I can raise the question again with a formal CEP when I have time to do something about it in terms of code... Dag Sverre
On Thu, Aug 18, 2011 at 11:35 PM, Dag Sverre Seljebotn <d.s.seljebotn@astro.uio.no> wrote:
On 08/18/2011 09:27 PM, Robert Bradshaw wrote:
On Wed, Aug 17, 2011 at 11:39 PM, Dag Sverre Seljebotn <d.s.seljebotn@astro.uio.no> wrote:
On 08/17/2011 09:21 PM, Robert Bradshaw wrote:
On Wed, Aug 17, 2011 at 11:46 AM, Dag Sverre Seljebotn <d.s.seljebotn@astro.uio.no> wrote:
On 08/17/2011 08:19 PM, Robert Bradshaw wrote:
That's a nice idea. I have to admit that all these special gil declarations are a bit messy. I'd also rather introduce clear decorators, e.g.
@cython.requires_gil # expects gil cdef a(): ...
@cython.requires.gil(False) # nogil cdef b(): ...
@cython.aquires_gil # with gil cdef c(): ...
(Actually, now that we have the "with gil" statement, it could be worth considering simply noticing the pattern of the entire function body in a with gil block/as the first statement and acquiring the GIL before argument parsing.)
Note that we need to declare functions as requiring the GIL to allow for declaring cpython.pxd if extern functions are implicitly nogil.
I agree, it's messy in the current situation, simplifying would be good.
Assuming we can't acquire the GIL in every single function just to be sure, I have a hunch that the "acquires_gil" aspect of a function is just declared in the wrong place. I mean, the same function might be passed as a callback to C both while holding the GIL and while not holding the GIL -- it would be nice to automatically wrap it in a GIL-acquiring wrapper only when needed.
So to me it makes more sense to have acquires_gil be part of function pointer types, or of the C call where the pointer is passed, or similar. Sort of like an FFI. Can't think of a practical scheme that's more user-friendly than the current way though...
I was thinking the opposite, "aquires_gil" should be completely transparent to the caller (assuming it's cheap enough to check-or-acquire, but that's an optimization not API issue). On the other hand requires/does not require does need to be visible to the caller though, which argues for it being part of the signature.
Are you saying that every single function cdef function, ever, that are not "nogil" should have acqusition semantics?
No, I was saying that the distinction between with gil and nogil should be transparent (semantically) to the caller.
Those semantics would be great, but I worry a bit about performance -- we just agreed to make function GIL-acquisition even a bit more expensive with that check...
According to your timings, the performance argument is a good one.
Hmm. How about this:
i) Every cdef function that needs the GIL to be held generates a GIL-acquiring wrapper function as well.
ii) Whenever taking the address of such a function, you get the address of the GIL-requiring wrapper, which can safely be used from any code, whether holding the GIL or not.
You mean GIL-acquiring wrapper, right?
Yes, sorry.
iii) However, Cython code that already holds the GIL can call the inner function directly, as an optimization. Should be possible to do this across pxd's as well.
iv) We may introduce a cython.nogil_function_address or similar just to provide an option to get around ii).
v) The "with gil" on functions simply ceases to take effect, and is deprecated from the language.
Regarding inference, are you thinking the semantics being that we (re)-acquire the GIL for every individual operation that needs it (including python operations or entire with gil blocks), with the obvious optimization that we may choose to not release it between (nearly) consecutive blocks of code that all need the GIL? That would be truer to Python semantics, but would require risky guesswork at compile time or some kind of periodic runtime checks. (It would also be a strongly backwards incompatible move, so as mentioned you'd need some kind of a explicit marker and deprecation period.)
No, I wasn't talking about this at all (this time on the list -- I did mention that I wished for this behaviour in Munich, but that's really long term).
All I wished for now was for simple code like this:
cdef double f(double x): return x**2 + x
to be callable without holding the GIL. In particular since this is the major reason why prange users need to learn the "nogil" keyword.
The semantics are simple: For all cdef functions, if "nogil" could have been applied without a syntax error, then it gets automatically applied.
Give that the implicit nogil marker is a function of the function's body, how would this information be propagated across pxd files? Perhaps I'm confused, we have
cdef double f(double x): # implicitly nogil return x**2 + x
cdef double f(double x): # implicitly "with gil" or implicitly "requires gil"? print x return x**2 + x
If "with gil" then constant, implicit gil acquisition could be a non-obvious performance hit; if "requires gil" then I don't see how to propagate accross .pxd files. (I do like the direction this is heading, just pointing out some cons.)
True, I didn't think about the pxd issue.
Brainstorming:
I) Downsize my proposal to within-module calls, require nogil for cross-module.
II) Change Cython so that any function can be called from within "nogil" sections (and then their GIL-acquiring wrapper, if any, will be called). Of course this is a little fussy regarding exceptions etc. and need some thinking through (which I haven't done).
Together with the proposal above to deprecate the "with gil" modifier and always generate GIL-acquiring wrappers, this works across modules: The module function pointer table gets two slots per cdef function; one to call if the GIL is held, and one to call if the GIL is not held. Functions that are nogil (explicitly or implicitly) then simply use the same pointer in both slots.
Sounds reasonable. Is there any scenario where one would explicitly not want the GIL-acquiring wrapper to be created/potentially used?
The only time this isn't completely safe is when the GIL is intentionally being used as a lock.
Or unintentionally being used as a lock... (Yes, that'd be user error.) The idea that adding a print statement to a function's body can produce such a large change is somewhat worrisome, but perhaps worth it.
My hunch is to postpone the question of inferring the nogil modifier. Instead, first focus on making the "with gil" modifier optional (GIL-acquiring wrapper on all cdef functions), and see where that takes us.
I guess I can raise the question again with a formal CEP when I have time to do something about it in terms of code...
Makes sense. - Robert
Robert Bradshaw, 17.08.2011 20:19:
I have to admit that all these special gil declarations are a bit messy. I'd also rather introduce clear decorators, e.g.
@cython.requires_gil # expects gil cdef a(): ...
@cython.requires.gil(False) # nogil cdef b(): ...
@cython.aquires_gil # with gil cdef c(): ...
The last would spell "@cython.aquire_gil", and yes, it totally makes sense to turn these into decorators. There's no reason at all why pure mode needs to differ from Cython mode here (however tricky it may be to write a GIL free function in pure mode...).
(Actually, now that we have the "with gil" statement, it could be worth considering simply noticing the pattern of the entire function body in a with gil block/as the first statement and acquiring the GIL before argument parsing.)
Agreed.
Note that we need to declare functions as requiring the GIL to allow for declaring cpython.pxd if extern functions are implicitly nogil.
Yes, I thought of that, too. In the specific case of .pxd files for external C libraries, a special "requires gil" syntax makes sense, as you'd want to put it at the "cdef extern" declaration once, instead of having to add a decorator to each of the declared functions. Stefan
participants (3)
-
Dag Sverre Seljebotn -
Robert Bradshaw -
Stefan Behnel