Do I need to use `nogil` in Cython

2024/10/14 1:13:04

I have some Cython code that I'd like to run as quickly as possible. Do I need to release the GIL in order to do this?

Let's suppose my code is similar to this:

import numpy as np# trivial definition just for illustration!
cdef double some_complicated_function(double x) nogil:return xcdef void func(double[:] input) nogil:cdef double[:] array = np.zeros_like(input)for i in range(array.shape[0]):array[i] = some_complicated_function(input[i])

I get a whole load of error messages from the np.zeros_like line similar to:

nogilcode.pyx:7:40: Calling gil-requiring function not allowed without gil
nogilcode.pyx:7:29: Accessing Python attribute not allowed without gil
nogilcode.pyx:7:27: Accessing Python global or builtin not allowed without gil
nogilcode.pyx:7:40: Constructing Python tuple not allowed without gil
nogilcode.pyx:7:41: Converting to Python object not allowed without gil

Do I need to find a way of calling np.zeros_like without the GIL? Or find some other way of allocating an array that doesn't require the GIL?


Note: this is a self-answered question designed to clear up some common misunderstanding about Cython and the GIL (although you're welcome to answer it too, of course!).

Second note: I've contributed enough to Cython that I should note it here (given that I'm bringing the topic up)

Answer

No - you probably don't need to release the GIL.

The basic function of the GIL (global interpreter lock) is to ensure that Python's internal mechanisms are not subject to race conditions, by ensuring that only one Python thread is able to run at once. However, simply holding the GIL does not slow your code down.

The two (related) occasions when you should release the GIL are:

  1. Using Cython's parallelism mechanism. The contents of a prange loop for example are required to be nogil.

  2. If you want other (external) Python threads to be able to run at the same time.

    a. if you have a large computationally/IO-intensive block that doesn't need the GIL then it may be "polite" to release it, just to benefit users of your code who want to do multi-threading. However, this is mostly useful rather than necessary.

    b. (very, very occasionally) it's sometimes useful to briefly release the GIL with a short with nogil: pass block. This is because Cython doesn't release it spontaneously (unlike Python) so if you're waiting on another Python thread to complete a task, this can avoid deadlocks. This sub-point probably doesn't apply to you unless you're compiling GUI code with Cython.


The sort of Cython code that can run without the GIL (no calls to Python, purely C-level numeric operations) is often the sort of code that runs efficiently. This sometimes gives people the impression that the inverse is true and the trick is releasing the GIL, rather than the actual code they're running. Don't be misled by this - your (single-threaded) code will run the same speed with or without the GIL.

Therefore, if you have a nice fast Numpy function that does exactly what you want quickly on a big chunk of data, but can only be called with the GIL, then just call it - no harm is done!


As a final point: even within a nogil block (for example a prange loop) you can always get the GIL back if you need it:

with gil:... # small block of GIL requiring code goes here

Try not to do this too often (getting/releasing it takes time, and of course only one thread can be running this block at once) but equally it's a good way of doing small Python operations where needed.

https://en.xdnf.cn/q/69471.html

Related Q&A

supervisord environment variables setting up application

Im running an application from supervisord and I have to set up an environment for it. There are about 30 environment variables that need to be set. Ive tried putting all on one bigenvironment=line and…

Updating gui items withing the process

I am trying to make a GUI for my app and ran into a problem: using PySimpleGUI I have to define layout at first and only then display the whole window. Right now the code is like this:import PySimpleGU…

UnicodeDecodeError with Djangos request.FILES

I have the following code in the view call..def view(request):body = u"" for filename, f in request.FILES.items():body = body + Filename: + filename + \n + f.read() + \nOn some cases I getU…

bifurcation diagram with python

Im a beginner and I dont speak english very well so sorry about that. Id like to draw the bifurcation diagram of the sequence : x(n+1)=ux(n)(1-x(n)) with x(0)=0.7 and u between 0.7 and 4.I am supposed …

How do I use nordvpn servers as python requests proxies

Dont ask how, but I parsed the server endpoints of over 5000 nordvpn servers. They usually are something like ar15.nordvpn.com for example. Im trying to use nordvpn servers as request proxies. I know i…

Python Proxy Settings

I was using the wikipedia module in which you can get the information that is present about that topic on wikipedia. When I run the code it is unable to connect because of proxy. When I connected PC to…

Docker - Run Container from Inside Container

I have two applications:a Python console script that does a short(ish) task and exits a Flask "frontend" for starting the console app by passing it command line argumentsCurrently, the Flask …

Way to run Maven from Python script?

(I am using Windows.)I am trying to run maven from a python script. I have this:import subprocessmvn="C:\\_home\\apache-maven-2.2.1\\bin\\mvn.bat --version" p = subprocess.Popen(mvn, shell=Tr…

Why does testing `NaN == NaN` not work for dropping from a pandas dataFrame?

Please explain how NaNs are treated in pandas because the following logic seems "broken" to me, I tried various ways (shown below) to drop the empty values.My dataframe, which I load from a C…

Python dynamic import methods from file [duplicate]

This question already has answers here:How can I import a module dynamically given its name as string?(10 answers)How can I import a module dynamically given the full path?(37 answers)Closed last yea…