478 points · by pablogsal · 3y ago · 499 comments
String parsing which tokenised in-place. DNS calls which used static buffers. Things which exploited Vax specific stack behaviour.
I think the GIL has been a blessing and a curse.
Around that time, doing cross-platform C++, I got an early look at Java, with concurrency built in from the start, along with GC and various other nice features that were easier to use than C++, and I "knew" it was going to be huge. (But who knew that the MIS people would take over Java, when it seemed clearly targeted at non-MIS programmers, and now MIS people are stuck with the C++ syntax and verbosity, after coming from 4GLs, etc.)
Then mainstream programmers picked up Python, which, IIRC, originally was an embeddable extension language, which was why it was simple. And for which the GIL made more sense.
For example, you can't safely use print in a Python signal handler, because the entire I/O system is not reentrant [1], yet the documentation shows doing this in a "how to do it properly" example [2] while explaining that it's horribly unsafe to throw from a signal handler, which is the default for SIGINT. (And also the reason why the threading module doesn't expose PyThreadState_SetAsyncExc). So despite appearances to the contrary (since the Python signal handler is invoked by the VM, it doesn't actually run in a signal handler context; the signal module registers a C handler which simply sets a flag that is checked by the VM every instruction), you should probably only do in a Python signal handler what you would do in C, which is very little. Set a flag or write to a pipe. Don't go around and call library functions.
[1] E.g. https://bugs.python.org/issue24283 [2] https://docs.python.org/3/library/signal.html#note-on-signal...
And Java doesn't even have good (conceptual) support for concurrency. Compared with eg Erlang, Rust or even Haskell.
But Java was still better at it than C or C++ at the time.
That's not even a contest. Java was released in 1995. At that time C did not have any kind of support for concurrency, all solutions were platform dependend and not part of the language.
Python was originally a teaching language, to replace BASIC and Pascal for kids and beginners.
(Yes, there once was a time when people took teaching programming seriously.)
Yes, van Rossum was an implementer of ABC, which was a teaching language. Python drew on that experience, but also from Modula-2 and Modula-3, and the needs for writing an extension language for the Amoeba operating system.
From the initial release notes at https://www.tuhs.org/Usenet/alt.sources/1991-February/001749... :
[Python is] an extensible interpreted programming language that
combines remarkable power with very clear syntax.
This is version 0.9 (the first beta release), patchlevel 1.
Python can be used instead of shell, Awk or Perl scripts, to write
prototypes of real applications, or as an extension language of large
systems, you name it.
No mention of it being a teaching language.> The letter “B” was chosen because it is the first letter of the word “beginner” and because the project was meant to become a language for teaching programming to absolute beginners.
[1] https://inference-review.com/article/the-origins-of-python
And between C++ and Rust coroutines, still not sure which one I like less.
hint:
% cd /usr/include
% ag --no-color '[^A-Z]_REENTRANT'No one's flipping a switch and breaking mountains of sketchy C.
Or you make the extra effort of being thread safe and you can declare your library as not requiring the GIL.
Now if a user script mixes your GIL free lib with an older lib that has not been updated, well, too bad for them. Even with your hard work, the code will still operate like before, everything gets the GIL treatment.
Normal python devs will need to track down which pesky dependency of their script is causing the GIL slowdown. Kinda sucks but at least nothing breaks.
It's a sensitive, opt-in, and safe way forward. Hard to argue against it, really..
How does one library support both GIL and no-GIL?
Easy, it supports no-GIL, so it supports both. Done.
If the burden becomes too big, at some point people may find it is the easier option to switch to a different ecosystem. I hope not.
I suppose the need to run your app in "no-GIL" mode is less than needing to jump from 2.7 to 3.
It also seems like the latter isn't meant as a replacement (for the moment), but rather as an option.
> We want to be very careful with backward compatibility. We do not want another Python 3 situation …
Entirely different from 2->3.
That analogy is so poorly applicable it's laughable.
Long term the plan is to 100% remove the GIL from python.
From the article:
> Long-term, we want no-GIL to be the default, and to remove any vestiges of the GIL (without unnecessarily breaking backward compatibility). We don’t want to wait too long with this, because having two common build modes may be a heavy burden on the community (as, for example, it can double test resources and debugging scenarios), but we can’t rush it either. We think it may take as much as five years to get to this stage.
Under base assumptions it also says:
> We want to be very careful with backward compatibility. We do not want another Python 3 situation, so any changes in third-party code needed to accommodate no-GIL builds should just work in with-GIL builds (although backward compatibility with older Python versions will still need to be addressed).
* update: I have also lived through 10 years of Python 2-3. It was not pretty.
Ugh, Nomenclature is hard
Because non-GIL compatible doesn't mean GIL incompatible
We're now up to 128 core CPUs, and even cheap CPUs have 6 cores on them. Restricting things to a single core's performance gets more and more limiting as time passes.
In Python you have whole C modules with global state. Load 10 of them, add the interpreter complexity and soon enough no one knows what is going on any more.
As it is, most developers (including core devs!) don't even bother to check for memory leaks. I don't think they'll run tsan, and if they do, it will be on a small test suite that only covers 10% of the code.
Given the software development practices in Python and especially in the AI space, I'm very pessimistic about this feature.
I also suspect that the GIL has saved us from debugging reentrant and/or dangerously concurrent code for years, and I salute the GIL for forcing us to build Arrow for IPC in Python, in particular.
Someday, URI attributes in CPython docstrings might specify which functions are constant time, non re-entrant, functions.
Reentrancy (computing): https://en.wikipedia.org/wiki/Reentrancy_(computing)
Global Interpreter Lock: https://en.wikipedia.org/wiki/Global_interpreter_lock
Even writing a JVM native JNI library would have allowed to avoid a lot of that pain (and the library would have been useable from Clojure, Kotlin , Scala, JRuby[1], Jython[2], Java, etc) without any painful threading issues.
[1] which I’m aware of having been used in production by companies in the past
[2] which I’m aware has been quite a bit under maintained for the last several years
I don’t think it’s false to say that the ease of moving hot spots into C is part of the reason Python has been so successful for thirty years.
I hope this works, but I am very sceptical about being able to port code that worked with a locking solution provided for the enthusiast trying out C working without running into concurrency bugs.
I distinctly remember that during the time period where Python grew from “minor” to “dominate” (roughly 1995-2005), doing Python dev was often a process of answering “are there bindings for that?” And usually _there were_, because of that tooling.
- The history is backwards: it isn’t that devs wanted to make a native library and then chose Python, it’s that they chose Python and then they needed a native library.
- Python works very well for scripts and small programs, and decently well for medium-size programs. This makes libraries with concrete purposes very useful and productive. If your library, say, helps devs do some basic calculation with time series, the ability to be used in quick scripts is a big plus.
- The C API is fairly good, and libraries such as pybind11 make it even better. You don’t need a lot of code or boilerplate for an extension.
Some of those do sufficiently simple things that they can run without any locking and all will be fine.
Others will still need locking, but are now under pressure to run without the gil. Some of those are going to do DIY locking within their own bounds.
Maybe what python has really been missing all these years is loads of ad hoc mutex calls scattered across the ecosystem. Data races and deadlocks introduced in the name of performance is not how I expected python to go out.
edit: expanding on this pessimism a bit.
Making C libraries written assuming a global lock thread safe is the sort of thing I'd expect concurrency experts to advise against and then make mistakes while implementing it. My working theory is that most people who wrote C extensions for python are not concurrency experts and are great programmers who won't back down from a challenge.
The data-race/hang/segfault consequences of this combination look totally inevitable to me. Python application developers are not going to love the new experience and I'm thankful my products are not built on top of the python ecosystem.
Many libraries have never had a multi-processing use case, others are so big that bugs are bound to happen, many of them subtle, so one guaranteed outcome will be unreproducible complaints and devs throwing in the towel. Opt-in will make people unhappy.
It seems like it could be a great outcome for developers.
> It seems like it could be a great outcome for developers.
For the ones that use certain libraries, not for those that have to build them.
For libraries that are reentrant but not thread safe, it should be sufficient to just add a global lock wrapping every call, which is pretty close to what the GIL was doing anyway.
It seems to me that in many (most?) cases it should be relatively straightforward to make existing libraries work without the GIL (at the cost of parallelism). I guess the main issue will be for libraries that call back into the python runtime from the C side.
never ever had a problem with GIL in python, always found a workaround just by spinning up ThreadPool or ProcessPool, and used async libraries when needed.
is there any use case of No-GIL which is not solved by multiprocessing ?
I thought Single threaded execution without overhead for concurrency primitives is the best way to high performance computing (as demonstrated by LMAX Disruptor)
No-GIL multi-threading is multi-core, though difficult to use. I don't know the Python implementation but shared memory should be faster than using multiprocessing.
That said, when designing a system from scratch, I completely agree with you that for almost almost almost all Python use cases, threads should never be touched and asyncio/multiprocessing is the way to go instead. Most Python programs that need fast multi-threading instead should not have been written in Python. Still, we're here now and people did write CPU-intensive code in Python for one reason or another, so no-GIL is practical.
In these threads, I also always see a lot of people who simply aren't aware of asyncio/multiprocessing. I assume these are also a significant share of people asking for no-GIL, though probably not the ones pushing the change in the committee.
This design scales much better for systems that will eventually overgrow one big machine. the No-GIL pytohn will be of no use, when you need to deploy your app across 100s machines.
I understand people want to take advantage of all cores etc, but at large scale - you will eventually need to split computation across machines and will resort to in-memory cache/queue anyways - so better just architect your system since day0
More machines is a multiplier. Instead of underutilising 1 machine, you'll be underutilising 100s of machines. More incentive to remove locking.
This will just allow people to waste even more compute resources to get somewhat quick results from Python instead of doing the right thing.
From an ecological viewpoint this PEP will be disastrous and keep entire power plants online.
IIRC some of the proposals around removing the GIL in the past have actually suggested that the asyncio paradigm could become multithreaded for parallelism.
Tons:
- A web server that responds using shared state to multiple clients at the same time.
- multiprocessing uses pickle to send and receive data, which is a massive overhead in terms of performance. Let’s say you want to do some parallel computations on a data structure, and said structure is 1GB in memory. Multiprocessing won’t be able to deal with it with good performance.
- Another consequence of using pickle is that you can’t share all types of objects. To make matters worse, errors due to unpickable objects are really hard to debug in any non-trivial data structure. This means that sharing certain objects (specially those created by native libraries) can be impossible.
- Any processing where state needs to be shared during process execution is really hard to do with the multiprocessing module. For example, the Prometheus exporter for Flask, which only outputs some basic stats for response times/paths/etc, needs a weird hack with a temporary directory if you want to collect stats for all processes.
I could go on, honestly. But the GIL is a massive problem when trying to do parallelism in Python.
> Manuel Kroiss, software engineer at DeepMind on the reinforcement learning team, describes how the bottlenecks posed by the GIL lead to rewriting Python codebases in C++, making the code less accessible:
> "We frequently battle issues with the Python GIL at DeepMind. In many of our applications, we would like to run on the order of 50-100 threads per process. However, we often see that even with fewer than 10 threads the GIL becomes the bottleneck. To work around this problem, we sometimes use subprocesses, but in many cases the inter-process communication becomes too big of an overhead. To deal with the GIL, we usually end up translating large parts of our Python codebase into C++. This is undesirable because it makes the code less accessible to researchers."
For average usage like web apps, no-GIL can be solved by multiprocessing. But for AI workloads at huge scale like Google and DeepMind, the GIL really does limit their usage of Python (hence the need to translate to C++). This is also why Meta are willing to commit three engineer-years to making this happen: https://news.ycombinator.com/item?id=36643670
Probably was easier to have one crack team of software developers write something new which could interpret all of the existing codebase, than it was to lead a widespread conversion of all of that code into faster languages.
ie. not everyone's a senior dev. There's reams more junior devs coming from bootcamps and such, computer science grads, etc, who can grok "scripting" languages like python and JS and Java much easier than they can pick up C++SIGSEGV or Rust algebraic data type smart pointer closure trait object macros.
Think how much of the world is boring "business logic" and it makes more sense - focus efforts making the [on the surface] simple, widespread, generalist, scripting languages, faster - we've seen it with Python, we've seen it with JS (node), we've seen it with Java.
Given how big the slow languages are, it makes lots of sense to save their CPU cycles compared to trying to hire from a much smaller pool of "competent at lower level programming" devs.
1. Because asyncio is completely useless when the problem is CPU bound, as the event loop still runs only on a single core. As the name implies, it is really only helpful when problems are IO bound.
2. Because sharing data between multiple processes is a giant PITA. Controlling data AND orchestrating processes is an even bigger pain.
3. Processes are expensive, and due to the aforementioned pain of sharing data, greenlets are not really a viable solutions.
The number crunching does, but distributing the workload, receiving results, storing and retreiving data, etc. doesn't. And these are huge losses in performance that could be avoided if we could parallelise them.
It's pretty nice to be able to just throw cores at a problem during prototyping phases, compared to throwing developer time to write native code.
This is a real problem-- which is why there's a whole lot of numpy/scipy maintainers in favor of the change.
Anything that benefits from both parallelism and replacing IPC overhead with shared data between parallel tasks.
I dont believe python will ever have atomic operations, even if it had - they still incur significant overhead for concurrency control.
sharing state between threads is such a narow niche use case, this pattern is practically solved by memcached/redis for larger scale python based systems
Yes, but there are plenty of problems where that is more development overhead, but less runtime overhead than IPC.
It is the norm. „Kafka scale“ problems are not the norm.
Outside of python, no it really isn't, it's the norm.
And even within python itself: That redis connection IS shared state.
I am thinking about multithreading every day to try make it easier to use. I journal about it in my ideas journals.
Threads let you use the same unified abstraction for parallelization and concurrency. They also make it easier to share state with parallelization (no need to go out of your way to do it) at the cost of requiring you to think about and implement thread safety when you do so.
Also, with no-GIL + threads the computational costs of creating and maintaining a parallel execution is much less vs multiprocessing. And data sharing and synchronization are less expensive.
What LMAX is doing is really just an overhyped way to speed up producer-consumer models. It might apply to your use case but it’s not the only reason you’d use parallelism or concurrency. I don’t even understand why they are claiming it to be an innovation when it’s just using a LockFreeQueue implementation within a pre-allocated arena? You also can’t synchronize with their implementation, which sometimes you really need to do. Not a silver bullet
1. random jumps in memory and branch misses
2. L1/L2 cache flush
3. context switch cost
4. concurrency locks cost
my understanding is that LMAX eliminated these costs: 1. pre-allocated arena ensures cache locality of operations
2. we dont jump form one sector of memory into another. Algorithm more resembles linear scanning of working memory set, and mostly within L1/L2 cache
3. no context switches, no cache flushes
4. no concurrency control costsLet’s say you did try to implement that in LMAX. It’s common for consumers/“workers”/what have you to require synchronizations amongst themselves, for example if they are operating on a shared k:v store of strings (operating an in-memory db let’s say). You can’t do atomic reads or writes on the thing so you need a locking mechanism; under LMAX you’d have to introduce another layer of producers to control reads and writes and then have another layer of consumers afterwards to handle the rest of your “consumer flow”, or wait in the original consumer thread for the producer to complete, which starts getting very wasteful and is certainly no better than a typical regular locks and context switching.
Again, this is not even a new thing. Lock free queues and “local atomic concurrent pub-sub” have existed for a long time - we have an implementation where I work. It’s not a perfect model even for where that concurrency pattern is wholly sufficient for what you’re doing either - the performance boost from the cache and context switching improvements have to be greater than the slack (in cost or throughput) introduced from producers or consumers sitting idle waiting for upstream data.
Also, context switches/cache invalidation/concurrency overhead can be avoided or at least greatly reduced by smart userspace scheduling a la fibers. With hand tuning it can potentially be completely eliminated (you can control which concurrency units to collocate on a thread and resume concurrency units/threads immediately after their waiting locks free) which is basically the same idea as LMAX. The problem of course, like with LMAX, is that doesn’t generalize.
> Python’s global interpreter lock makes it difficult to use modern multi-core CPUs efficiently for many scientific and numeric computing applications. Heinrich Kuttler, Manuel Kroiss, and Paweł Jurgielewicz found that multi-threaded implementations in Python did not scale well for their tasks and that using multiple processes was not a suitable alternative.
> The scaling bottlenecks are not solely in core numeric tasks. Both Zachary DeVito and Paweł Jurgielewicz described challenges with coordination and communication in Python.
> Olivier Grisel, Ralf Gommers, and Zachary DeVito described how current workarounds for the GIL are “complex to maintain” and cause “lower developer productivity.” The GIL makes it more difficult to develop and maintain scientific and numeric computing libraries as well leading to library designs that are more difficult to use.
Let's hope the change is not this badly mercenary.
I mean a situation like where in threaded context there would be code like:
def determine_quest_latency(quest_name: str) -> int:
return other_thread.wait_sync_job(lambda context: context.ping_quest(quest_name))
..without needing to provide a protocol that covers each possible scenario the client might wish to execute in the process?I believe the answer is "you don't", but passing functions in messages is a highly convenient way to structure code in a way that local decisions can stay local, instead of being interspersed around the codebase.
If you really want to pass lambdas, you can use a third party library to pickle them
https://github.com/cloudpipe/cloudpickle
Yes, this is not great.
You can have shared-memory parallelism with near-zero synchronization overhead. Rust's rayon is an example. Take a big vector, chunk it into a few blocks, distribute the blocks across threads, let them work on it and then merge the results. Since the chunks are independent you don't need to lock accesses. The only cost you're paying is sending tasks across work queues. But that's still much cheaper than spawning a new process.
But I have the same question as you have if we add another coming concurrency model: SubinterpreterThreadPool, which will be possible with the per-interpreter GIL in python 3.12 and later.
That's another new model that is already confirmed to be coming: interpreters (isolated from each other) in the same process, that can run with each their own GIL.
with PoC of the parallelization code being developed here https://github.com/jsbueno/extrainterpreters
Multithreading is more efficient but more difficult to work with.
You share the same address space in threads, so you can communicate any amount of data between threads instantly within a lock. The same cannot be said for network traffic or OS pipes or multiprocessing.
Multiprocessing uses pickle to serialize your data and deserialize it in the other python interpreter.
If you start a Python Thread, you're still single threaded due to the GIL.
Multiprocessing does the parallel computation pretty well as long as the granularity is not too small. When smaller chunks are needed most of the time that's something better done from an extension.
For creating stateless, mostly IO bound, servers, it's great. Try to squeeze in performance and it all starts to fall apart.
People using C extensions may also rely on them executing atomically. For example, you could have a thread pool that posts and receives from a numpy array. Would work fine today but break without the GIL.
It just means for the brave few that flip it on and use it, be prepared to spend a huge amount of time finding and fixing subtle race conditions in decades of old python library code. The early adopters are going to be in for a lot of pain, or more likely they'll restrict their use of non-GIL processes to very specialized and dedicated processes that have as few dependencies as possible.
To quote Guido:
>Let’s not blow it this time. If we’re going forward with nogil (and I’m not saying we are, but I can’t exclude it), let’s make sure there is a way to be able to import extensions requiring the GIL in a nogil interpreter without any additional shenanigans
https://discuss.python.org/t/pep-703-making-the-global-inter...
The argument against this seems mainly that it's a lot of work; not that it's impossible work. It probably is a lot of work but if there are enough people doing the work, we should get some results.
As someone who works professionally on a parallel / async runtime that supports thousands of continuously running servers, "extremely unlikely" means that actually it breaks all the time, but it's also impossible to debug.
No-GIL is a much smaller shift. It can follow the same transition path without radically breaking things. And if some things do break, there would be a well-defined way to handle those cases.
We all somehow survived those. Glad to see forward motion on this. It will open up a lot more terrain that has been marked off as untenable.
One of the things about early Swift that they got right was building breaking changes into the promise. Everyone knew where they stood and adjusted just fine. Sometimes I wish Python would take the same path.
A lot will depend on the Python community and the distribution channels. I could see the community struggling to adopt it in a timely fashion, or distributions jumping the gun (Ubuntu, Fedora, Anaconda). Maybe it's too early to make hard decisions, but how much control does the SC really have to avoid such a scenario?
That is too long for Python to have 2 modes. Half a decade is more than enough time for 2 modes to become the status quo. For one thing, think of all the outdated Stackoverflow threads that will be hanging around after that 5 years. I am not optimistic that 5 years won't turn into 10 years of uncertainty and breakage.
But 5 years might be too short for everyone to dredge up all that C code, update it, test it, and call it mature.
I guess we'll see.
Developers are lazy. Most people will just do nothing until, 5 years from now, some blog post will go "oh, next month we switch noGil as default, good luck!". At that point everyone will scramble, rush out buggy releases, and spend 5 years finding all the problems.
But apparently Python needs some "success" and this makes a good bullet point. Correctness does not really matter in the Python world.
The unicode/text changes alone were a pretty good reason. Division producing floats are also a nice change IMO. I don’t want to discount the challenges with the transition but saying there was no good reason isn’t right to me.
They’ll have to be intensely careful not to accidentally affect yes-GIL behaviour. All kinds of weird cases are possible if any sort of emulated GIL isn’t exactly like with a GIL.
1. We don’t want it to be.
2. We’ll give up quickly if it is.
Those are both important points. But there seems to be an important missing third piece of “and we’ll achieve this by…”.
>I didn't dive deep on this, but I assume that GIL mode can still run anything, including no-GIL code (it is one of their promises, at least). So, unlike 2->3, there is forwards-compatibility.
>It also seems like the latter isn't meant as a replacement (for the moment), but rather as an option.
As long as GIL mode remains compatible with both old and new code, I see very little danger in having a no-GIL mode (besides hogging CPython maintainers' time).
currently quite a lot of companies use python3.6 only because it comes standard with the Ubuntu 14.04.6 which happens to be the oldest LTS version - and companies have habit of migrating from out-of-support LTS version to currently-supported-oldest-LTS
this can repeat 2->3 because there will be users stuck with older versions of python and library maintainers will have to maintain both versions: with GIL and without GIL (just like PHP extension developers did with thread safe methods)
For any tool builder that means their cost has just doubled for the next five years, at least. Why? Because people will want to use tools in either mode, no matter if it is deemed productive or experimental.
1. In which version No-GIL will become default option in CPython
2. When that CPython version will come standard in LTS Linux distro
3. When all earlier LTS distros will go out of support
4. When companies switch from outdated to target LTS version of distro
currently quite a lot of companies use python3.6 only because it comes standard with the Ubuntu 14.04.6 which happens to be the oldest LTS version - and companies have habit of migrating from out-of-support LTS version to currently-supported-oldest-LTSGood explanation here: https://realpython.com/python-gil/
1. There are some improvements worth breaking reverse-compatibility for, and removing the GIL is such an improvement. Whether the changes in Python 3 were worth making breaking changes for is debatable: certainly I don't see "print" being a function as particularly valuable. But the flipside is that the 2-to-3 transition was overblown by a vocal minority. I've transitioned more than 5 codebases from 2 to 3, and in most cases, there were few problems. Most problems were with codebases where previous developers had pulled in libraries for everything, resulting in an amalgamation of abandoned libraries, but these codebases run into problems even without the core language breaking compatibility. The answer isn't to flame your language into never breaking compatibility, it's to not import all of pip and expect that to be a sustainable strategy.
The situation we have now is that the steering committee has received so much heat from the vocal minority that they're terrified to make breaking changes. But removing the GIL should be a breaking change. It's too fundamental to how Python works to not be. So they're trying to remove the GIL and make it not a breaking change, which is a bad idea, because it is ultimately going to be a breaking change. It would be much better to admit this is a breaking change and start working on the transition plan, than to try the impossible task of making it not breaking because you're too terrified of your users to admit the truth.
We've already seen this in Python 3.11 which broke code in my codebase. The changes to fix the breakage weren't hard, but I would have liked better communication that this might happen. But I also understand why this was hidden in a deprecation warning in a minor release rather than publicized, because the Python team is probably tired of being flamed for making breaking changes.
2. The more fundamental problem here is that a lot of other features of Python were built around the GIL. Most obviously, the async paradigms makes sense largely because of the GIL. Sans-GIL, it looks like in retrospect a send/recv actor model a la Erlang would have been a much better way forward. It's not really possible to reverse this, and this might be pushing Python toward a less cohesive set of features that don't really make sense together. This makes it feel like this is too little too late.
I greatly welcome true multithreading in Python.
I use both multiprocessing and multithreading in Python for different projects. See [0] for my multiprocessing example and python Threads for IO heavy tasks in [1]. But it would be far more efficient to use true threads.
Threads can communicate any amount of data in a single atomic almost instant operation. Using the local loopback interface or multiprocessing or pipes, this is not possible.
I am working on a multithreading architecture I call three tier multithreading architecture
https://github.com/samsquire/three-tier-multithreaded-archit...
My goal is extremely scalable and performant servers but Python is probably the wrong job for that.
[0]: https://news.ycombinator.com/item?id=36897054 (my description of my use of multiprocessing) [1]: https://devops-pipeline.com/ (my use of multithreading)
The chosen solution is similar to how PHP used TSRMLS_ macros in the Zend engine - if threadsafety (ZTS) was #defined, all functions took an extra thread context parameter, breaking ABI.
The new PHP 8 fibers are only coroutines on a single thread, but PHP has had fork/join since 2001 (!), which works pretty well with Linux CoW.
There has been a pthreads extension since about 2012. However keeping a 1:1 pthreads API prevents some optimization possibilities [1], so the new hotness is php-parallel [2], which will transparently copy closed-over variables to a subinterpreter.
1. https://github.com/krakjoe/pthreads/issues/929#issue-4106367...
A similar misunderstanding exists about SQLite and concurrency.. but that's a topic for another time.
Please explain: In what sense is the overhead of starting actual OS processes, and relying on IPC "free", compared to running threads or even greenlets, and using shared process memory?
With Python's current multiprocessing utilities - you get a big discount by not having to write thread-safe code, or worry about synchronization, despite the GIL still being there. Very broadly speaking, it's "free" in the sense that the OS handles parallelism automatically at the process-level, and provides a simple communication mechanism between those processes through standard APIs. It also reduces potential attack surfaces (although this is a lesser argument).
It's also "free" in the sense that you don't need to re-write large parts of the VM, as-well as all supported libraries, and teach the entire Python community how to safely write and test multi-threaded code (something I bet upwards of 75% of the people using Python today won't manage) to support this specific form of parallelism.
If your goal is to run code (whether IO bound or CPU bound) in parallel - Python has the means to do that already today, without removing the GIL.
And when it's not ?
IPC is a PITA, and orchestrating processes is even worse.
> or at the isolated numeric library level
Not everything I want to parallelise in python runs in numpy. Simple example: WebService Backends. I have a 64 core server running a Werkzeug/Gunicorn application. The Service is mostly doing CPU bound tasks (data aggregation and analysis), so asyncio is pointless.
What happens is, it runs 60 worker processes. Which puts hefty limitations on any crosstalk and data sharing, because these either require IPC, or using redis/sql. Which are nowhere near as performant as actually shared memory would be.
I think, rightfully, the concern is people who will try to use this incorrectly causing major bloat to CPython.
Please explain who exactly is "drawn into this"?
If you want to use async, this change doesn't affect your code.
If you want to use multiprocessing, this change doesn't affect your code.
Even if you already use threading, and do it correctly, this change doesn't actually affect your code.
So who is "drawn into this"? And please don't say library developers. a) Having to update libraries to have them remain relevant, is normal procedure, in all languages. b) a lot of the people who want this to change are library devs.
Whatever this comment means (I honestly can't properly tell) - removing the GIL will have absolutely no impact on Python's resource utilization.
Quote: "In PyTorch, Python is commonly used to orchestrate ~8 GPUs and ~64 CPU threads, growing to 4k GPUs and 32k CPU threads for big models. While the heavy lifting is done outside of Python, the speed of GPUs makes even just the orchestration in Python not scalable. We often end up with 72 processes in place of one because of the GIL. Logging, debugging, and performance tuning are orders-of-magnitude more difficult in this regime, continuously causing lower developer productivity."
Quote: "We frequently battle issues with the Python GIL at DeepMind. In many of our applications, we would like to run on the order of 50-100 threads per process. However, we often see that even with fewer than 10 threads the GIL becomes the bottleneck. To work around this problem, we sometimes use subprocesses, but in many cases the inter-process communication becomes too big of an overhead. To deal with the GIL, we usually end up translating large parts of our Python codebase into C++. This is undesirable because it makes the code less accessible to researchers."
In Python there's a much better option if you care about performance - use a different language!
The website you're using likely benefits immensely from thread-safe code. The browser you're using benefits immensely from thread-safe code. Your entire user experience using the modern internet is in an ecosystem of thread-safe code which you apparently are completely oblivious to.
There are a lot of threading models besides Java and C's as well, which you're apparently also unaware of.
Why would you assume you know all the possible use cases of a multi-purpose programming language?
PYTHONGIL is an awkward tri-state. 0, 1, and unset all do different things. Wouldn’t some self-explanatory strings be better? PYTHONGIL=auto for the default, force-gil and force-nogil for the forced modes.
What?
Python could have been the one language with a sane multithreading model. Now it risks becoming a second version of Java. I fear this will make it a less attractive programming language, not least because it might lose its beginner friendlyness. For example, without the GIL a lot more care must be put into designing your programs. This can be true even though your own code is single threaded, for example when you use a library that is multithreaded and has callbacks to your code
Why?
Free threading as introduced by PEP 703 is well known to be errorprone, hard to get right and generally advised against, unless you know exactly what you are doing. In other words free threading is for expert (as in very experienced) use only. And Python already has an expert mode - called Cython oer Numba to name just two.
Personally I can see no good will come from bringing free threading to the masses. Yes it addresses a common critique (by many) and need (by very few), but it addresses it in a very risky way (for the vast majority of Python users).
A better alternative
IMHO the far better and still my preferred approach would have been to favor a per-thread GIL with an explicit mode to share particular objects. This would benefit everyone without the risks. It would be consistenly beginner friendly, and above all, offer a safe path to concurrent programming without impacting the whole ecosystem. Heck we could even call it the "Pythonic Threading Model", and it would be seen as a differentiator.
If you don't care about CPU performance, instead of threads you should go for an event-loop approach (see asyncio in Python). As soon as you have threads (on a language-level, not implementation-level), there is some notion of implicit switching, and you run into issues. So, the language you're looking for is JavaScript, which is single-threaded and every context switch is explicit (in form of `await` or `yield`).
Like, for example,
count += 1
---The GIL primarily protects C code, not Python code.
The author literally says: "This was actually pretty hard to discover. The first few experiments failed, because Python is pretty smart about when it runs each thread."
But I think the main way the GIL protects inexperienced users is that its presence has the effect that Python code using the threading APIs is very uncommon, since those APIs don't currently provide parallel computation (only parallel IO). So inexperienced users are protected due to 99% of Python programs not using multithreading as a result (and so likely the one they're developing also doesn't), whereas this will presumably change when the limitations imposed by the GIL go away.
> The author literally says: "This was actually pretty hard to discover. The first few experiments failed, because Python is pretty smart about when it runs each thread."
I completely disagree here with your reading. Rare race conditions are much worse than races you trip over frequently.
First, I don't see how the GIL would have much to do with free multithreading. The GIL should not have much observable logical impact on multithreaded _Python_ code. It should not make it more or less susceptible to race conditions. It's only practical impact should be slowness.
Second, your proposed "one GIL per thread" is pretty much the equivalent of the current state of multiprocessing. In that you fork your current interpreter state in an other thread with it's own GIL and start from there. This has been used for decades already, nothing new there. Sharing can be done through queues or shared memory.
No, no the same thing. Sharing objects between processes is not easily achieved for various reasons (at least in Python). It would be easier to get it in multithreading with an arena based allocation model where objects live in a shared or non-shared area of memory.
Also it's not my idea. I am just advocating it as the better model for Python to advance to. It would also not take years to implement and the risks are minimized as there is full compatibility with existing code.
Well to me it is the same thing.
Two threads sharing state through a common heap, or two processes sharing state through a shared memory is pretty much indistinguishable, at least on Linux.
The question is not multithreading or multiprocessing anymore, the difference to me is more semantic than real.
The question is then just how these threads/processes communicate.
I would argue that shared mutable state is rarely a good idea, and an equivalent message based system is often preferable.
For the few use cases that remain where you would want shared mutable states, as mentioned in my original answer, Python has shared memory support, though with non-built-in types. Improving these shared types should be the only thing you advocate for.
That still relies on IPC, and the associated kernel overhead to set, ctl and access the shared memory, IN ADDITION to the kernel overhead of having to do a context switch between processes.
Threads only rely on the context switch.
> I am just advocating it as the better model for Python to advance to
https://discuss.python.org/t/poll-feedback-to-the-sc-on-maki...
It has nothing to do with multithreading or GIL, though, and happily works without threads and with GIL in place.
I’ve often thought that proper threading should be learned by the masses, not to be scared of it. This sort of statement does nothing but spread FUD.
It’s like saying that C is a safe language, just “get good” at it.
There are safe alternatives such as structured concurrency.
... or at least it should be public knowledge that anything prefixed with "async" is windows 3.1 multitasking from the 90s...
Why are we getting 64+ core servers to run single threaded cooperative multitasking on them? :)
Alternatively, message-passing isn't traditional threading, but Erlang/Go-style languages are another way to approach concurrency or parallelism.
You just described Ractors in Ruby, which didn’t turn out great. The setup cost for either freezing or copying memory to the target ractor to guarantee memory safety is often higher than the perf gains of the parallelism.
Not that it can’t work or won’t be improved. But there is a real world case study of what you’re recommending that we can reference without having to guess.
You should hear about async...
;)
From what I understand, this is how threading worked in perl. But that functionality is now "discouraged".
I do think that would have been a good way to do it. Especially with an emphasis on message passing.
>offer a safe path to concurrent programming
Uh, doesn’t Python support this already? Python has “concurrency” from async and parallelism from multiprocessing. What it doesn’t support is thread-based parallelism. What you’re suggesting (if I understand it) is an implementation of parallelism that is barely different at all from the typical Python parallelism approach of using multiprocessing to achieve parallelism.
This is like Ruby's Ractors and I haven't really seen that be super successful so far. The "Objects" that need to be shared are things like class definitions, etc.... there are a ton of subtle issues with objects that are being marked as sharable when they should really not be or vice versa.
All of the multithreading bugs without any of the multithreading performance.
Just like you can today spawn threading.Threads one by one in python, or just map a bunch of function calls over a threadpool using concurrent.futures thread pool.
It's simply not "sane multithreading" not being able to run Python (byte)code concurrently. It's just a huge annoyance.
> because it might lose its beginner friendlyness
Python is not beginner friendly. It has one of the worst documentations out there. Also it does things very different compared to other languages (C#, PHP, Java, JS, ...) - I would advise anyone against learning Python as their first language, while Python is my favorite language.
> And Python already has an expert mode - called Cython oer Numba to name just two.
CPython is the "official" Python. How is it beneficial to depend on some 3rd party projects? I don't want to use such projects.
As to the PEP itself: It's optional, with the GIL being enabled by the default. So what's the problem...
Please read my post again. I am advocating a GIL per-thread model with an explicit feature for sharing selected objects. This allows for all cores concurrency, essentially like free threading yet with safeguards. I like to call that a sane way because it builds on decades of research and industry experience of the software engineering community.
> As to the PEP itself: It's optional, with the GIL being enabled by the default.
It's not optional if you build tools and libraries that need be able to run with both gil and no-gil.
Is there a PEP or something written about it? I don't like this idea at first glance. Feels like another hack. Though I have to admit it sounds better than the annoying multiprocessing approach.
> It's not optional if you build tools and libraries that need be able to run with both gil and no-gil.
Why do they need to? A library dev is free not support one or the other? If a library then does not provide the preferred mode of the user, then that's bad, but that's life. Ideally most libraries will support a gil version (that's still the default anyway!), but provide a no-gil version as a bonus. For example, Pytorch could provide thread-based data loaders if the no-gil version is in use.
* Threads are also relatively fat. You'd probably think twice about spinning up 1000 of them.
* Futures came in with Java 8 and are lighter weight, but have certain implementation defects - can't cancel them for example. Although there are some instances in which regular threads aren't cancellable. Also, the API isn't terribly popular. I happen to like flatmapping my way around a codebase, but plenty of devs' eyes glaze over when they read that code.
* Fibers are released I think - at least in beta. More like JS's model I believe. They're even lighter weight and get rid of the flatmappy stuff again. I assume it's still up to the programmer to get the locking right.
https://discuss.python.org/t/a-fast-free-threading-python/27...
That doesn't follow; you're assuming that Python should prioritize performance as a top priority, which is very much not a given. Python has always excelled at being easy to use, being flexible, being a great glue language - but performant? An interpreted, dynamically typed language? That's like making a C interpreter - you can do it, but that doesn't make it a good idea.
And yet despite your complaints, JavaScript, Lua and Julia continue to rise in popularity.
After enduring the arduous process of migrating from Python 2 -> 3 and navigating the complex world of dependencies, my hope is that we won't encounter another nightmare of dependency management, forcing users to choose between GIL and no-GIL builds.
Please tell us: What other solution do you propose for running CPU bound workloads in parallel?
There are exactly 2: Multiprocessing and using another language.
Why should Python even have a free threading model?
Regardless, we did somehow end up here, and there's plenty of multi-threaded Python code that would benefit from no-GIL, so I support the proposal just from a practical perspective. But when designing a new codebase, you'll almost almost almost always want to avoid Python threads, even with no-GIL.
...is useless for CPU bound tasks. The event loop uses only one core.
> multiprocessing
...relies on IPC and running actual system processes, both of which have alot more overhead than switching thread context and using shared memory.
> For any use case where the last few percent matter, consider not using Python (which will be much much more significant).
Here is an interesting question: If asyncio and multiprocessing already give us "nearly the same or better performance", then why is "use another language" such a common advice to escape parallelism-problems in Python?
Because, curiously enough, the languages that are usually recommended for this (C, Go, Rust, C++, Java) all implement thread-based parallelism.
I'm afraid we'll soon learn its not the version # that's burdensome, but the real or perceived(!) incompatibility between versions.
I wonder if introducing such a monumental change in a build flag of the minor version is really wise. Certainly its not in line with any interpretation of semantic versioning (to be fair I think the PSF does not claim to use that).
I think new language features shouldn't just be added to provide syntactic sugars or coding shortcuts to programmers or just because a certain feature has become very cool (like lambda functions, for eg).
I'm glad that the Python community has realized that performance is an issue and started working on things like no-GIL mode.
People often say that Python's biggest strength is its readability and easy syntax but I disagree. Python's real strength is the enormous third party library ecosystem, popular packages like numpy, pandas, scikit, etc. which have almost become addictive in most data science projects. But now, people are thinking of other alternatives to these due to Python's performance issues. Other ecosystems like golang and rust are getting built at rapid pace and at some point, they will also have (more performant) equivalents of these packages if public shows enough interest.
> Basically for the moment the GIL-less idea would likely be burdensome for us and the fact that it's only an "option" seems to strongly imply major compatibility issues that we would not prefer.
(...)
> Adding an entirely new mode of operation to cPython that's optional would be an enormous burden for us as far as ensuring we use APIs appropriately, adding support, testing, we would have to spin up new test workers to test SQLAlchemy in both modes of operation, we would be getting strange new race condition related issues reported
https://github.com/sqlalchemy/sqlalchemy/discussions/10002#d...
Ruby could learn a lot once this is done, but at the moment GIL optional in python seems to be a 2030 goal.
- library author marks their library "no-GIL" after making sure it's thread-safe without GIL
- if the interpreter sees this metainformation, it temporarily disables GIL for the current OS thread while running the library's code
- result: old versions of Python can still run no-GIL libraries under GIL, while new versions of Python allow to gradually remove GIL
Or it's not how CPython works?
giving up this stance? a lot of code is instantly a legacy, and a lot of it is a legacy people won't even know about before they notice the problems. and for what?
i must say that i have no experience running Python without GIL so my idea of the ways things can be not thread-safe is purely speculative/borrowed from very different languages (that I finally moved on to long ago, thank god). so maybe i'm wrong, i misunderstand the impact, and all this code is just fine
In the future the default concurrency model will be shared everything free threading, and all hell might break loose. Hopefully not.
I hope it'll be recognised by the most "host" applications (uvicorn or whatever) that multi-threading is not a good idea anyway and they'll discourage it. But there'll definitely be a macho-land of thread-"safe" programmers whose bugs we'll be downstream of
Like asyncio's introduction we'll probably see core stuff like http requests, file IO etc. all now have an entirely new permutation of libraries made to support non-GIL mode. This is going to get pretty spicy as stuff like http already has regular (blocking IO) and asyncio (non blocking IO) versions, so now do they need regular non-GIL and asyncio non-GIL versions too? Is the default for a library author going forward to be creating four permutations of your library with vastly different behavior in each of them? Yuck.
And someone may prefer to make NON GIL wall of shame/fame instead of directly contributing to those libraries
;)
It’ll make the Python source code much more complex and complicated, which is probably not a big deal, though I’ll say the CPython source is quite brilliant.
It’ll also mean for C library developers that they can’t assume Python opcodes are atomic. But I’m not sure C library developers will really mind too much because they already worry about this kind of stuff.
The underlying pressure on the Python ecosystem is to transition to a post-Moore's law era and effectively become a HPC platform where the "same" code runs on a CPU, a GPU, multicore, clusters etc.
Python may feel the pressure more than others because of the GIL and the fact it is used in compute intensive tasks more than others.
But this major need to transition to easy and seamless HPC/heterogeneous computing is the same for all languages. The question is who will get there first.
Lex Fridmans podcast had an interview with one of the creators recently. Chris Lattner, who is also the creator of LLVM and Swift. Recommended listen for those who haven’t heard of mojo yet, if you have 3h to spare.
- How much does performance improve due to this No-GIL thing? Is it greater than 2x? For what workloads? - Do I have to compile two versions of every extension (gil/nogil)? I would prefer building extensions does not get any more complicated. - Can I automatically update my code to handle nogil? (a tool like lib2to3 or six)
That being said, this is interesting.
Can we get an in-python fork() mechanic ... please?
The old method — which is the GIL, or non-non-GIL — provides no thread safety to Python code. It only protects C code
> Can we get an in-python fork() mechanic ... please?
You probably want Multiple Subinterpreters: https://github.com/python/cpython/issues/84692
Non-GIL adds some complexity to the implementation and some risk when writing multithreaded code at the benefit of improving performance.
No-GIL means it is possible to run things in parallel (without resorting to fancy C extensions).
The same is true for multiple processes, yet that is much easier to reason about and a lot more likely to get it right.
I get that it's a hard problem, but it isn't a guessing game. Concurrency has always required one to carefully design their program. We will see how Python implements these new APIs, but I trust it will be approachable to those who want to do it.
What is the use case for this?
Who needs it?
I _am_ a python programmer.
> What is the use case for this?
> Who needs it?
This can be answered with a simple user story:
As "THE PYTHON STEERING COUNCIL",
I want to "GET RID OF THE GIL",
so that "PEOPLE WILL STOP WHINGING ABOUT THE GIL."
To be fair, there's another group of people who stand to benefit. Namely, any python programmers who currently believe that "threads are an easy way to make my program go faster" will soon be the recipients of a valuable learning experience.
;)
They will approve something if it serves a corporation. The submission here is likely CYA, so they can say that "they asked the community".
There is no appreciation for people doing grassroots open source software. If Instagram can add another hack instead of switching to Java, it will be approved.
It is important to remember that paid corporate developers will have job security every time new pain is introduced in the Python ecosystem.