841 points · by zorgmonkey · 5y ago · 358 comments
In an alternate Python timeline, asyncio was not introduced into the Python standard library, and instead we got a natively supported, robust, easy-to-use concurrency paradigm built around green/virtual threading that accommodates both IO and CPU bound work.
Minus the "natively supported" part, we have this today in http://www.gevent.org/ ! It's so, so empowering to be able to access the entire historical body of work of synchronous-I/O Python libraries, and with a single monkey patch cause every I/O operation, no matter how deep in the stack, to yield to your greenlet pool without code changes.
We fire up one process per core (gevent doesn't have good support for multiprocessing, but if you're relying on that, you're stuck on one machine anyways), spend perhaps 1 person-day a quarter dealing with its quirks, and in turn we never need to worry about the latencies of external services; our web servers and batch workers have throughput limited only by CPU and RAM, for which there's relatively little (though nonzero) overhead.
IMO Python should have leaned into official adoption of gevent. It may not beat asyncio in raw performance numbers because asyncio can rely on custom-built bytecode instructions, whereas gevent has "userspace" code that must execute upon every yield. And, as with asyncio, you have to be careful about CPU-intensive code that may prevent you from yielding. But it's perfect for most horizontal-scaling soft-realtime web-style use cases.
Then came Asyncio, which I personally disliked for the simple reason it became so popular that everybody thinks it's necessary to write an asyncio version of their library/module. The result is it now tears everything in 2. Asyncio code and non-asyncio code ...
Everything like Asyncio, Curio, Trio are impressive and interesting but their interfaces are way too involved for the intended result and it should never be like that. (Gevent suffered less from that).
The only way forward is proper thread support without the GIL and therefor I applaud this effort.
> gevent doesn't have good support for multiprocessing
This is where my little library https://github.com/jgehrcke/gipc might help! It's been working well for people since 2012 :)
By the way, gevent is huge for the Python ecosystem and I would love to acknowledge both Denis Bilenko and Jason Madden who have done a great job over the years. I am in particular impressed by Jason's maintenance work -- creating a new project is always exciting. Maintaining it over the years is sometimes just tedious, hard work. Jason has impressed me a lot with his one man show there.
Not sure if everybody knows, but gevent was for starters built on top of "only" libev -- another super impressive project built and maintained by practically a single person: Marc Lehmann. I learned a lot from his work, too. So so so many serious software projects build on top of libev.
Only 'recently' gevent included support for libuv, the event loop that originated from the NodeJS ecosystem.
I find it super interesting to see that CPython+gevent+libuv is highly similar to running NodeJS!
By the way, the LWN article is once again a wonderfully written piece by Jonathan Corbet. His way to doing technical writing is simply great, I have enjoyed it very much over the years and learned a lot.
Are you able to fully utilize a multicore processor? I'm not familiar with gevent.
uWSGI supports gevent https://uwsgi-docs.readthedocs.io/en/latest/Gevent.html
Falcon also benefits from Cython acceleration. It's been a while but at the time I tested against PyPy and either it was slower or had quirks I was unable to resolve (don't recall w/o consulting my notes).
The OP is trying to solve the GIL problem, which is saying: "activity on other threads, which might touch objects in memory that my thread cares about, shouldn't keep my current thread from doing useful work." Right now, Python needs to be super conservative to keep threads from stomping on each others' memory, and this should make it a lot more feasible to do that in a sane way. As the comments in the OP post itself suggest, though, this isn't necessarily a sufficient solution. If you're looking for the real solution to "let other threads borrow my memory without global locks," the Rust language and its borrow checker is really the holy grail there.
Regarding gevent exceptions, I find them actually quite natural to work with. If you're looking at old tutorials that talk about linking callbacks to handle exceptions, in practice I've never needed to do that - that stuff is primarily useful to those writing things like gunicorn itself. Pool.imap[_unordered], greenlet.get(), and more will simply re-raise exceptions in the caller's greenlet if there are exceptions in the farmed-out greenlets. And if you need even more control, you can try-catch within the functions that are running inside your greenlets, and return results that may either be a success or a failure.
Added: I don't understand the downvotes. If Python 3 was going to make an incompatible departure from Python 2, they might as well have done stuff like the above, that brought real benefits. Instead they had 10+ years of pain over relatively minor changes that arguably weren't all improvements.
I think it's important to remember the difference between parallelism (trying to compute faster by using multiple cpu's simultaneously) and concurrency (communicating on multiple communication channels that are sending stuff non-deterministically). The GIL gets in the way of parallelism but except in extreme cases, it doesn't interfere with concurrency.
It took less than a day to migrate all my code to Python 3. And by "less than a day" I mean "less than 2 hours". Granted, bigger projects would take longer, but saying stuff like "10+ years of pain" is ridiculous. Probably less than 1% of projects had serious issues with the migration. We just hear of a few popular ones that had some pain and assume that was representative.
I myself never bothered migrating any of my Python 2 stuff. It might not be difficult to do so, but continuing to run it under Python 2 still works fine. If you migrated all of yours in 2 hours, you must not have had much to start with.
I do use Python 3 for new stuff most of the time by now, but I keep running into little snags, like the .decode() method not working on strings, or having some (but not all) of the codecs removed from the string module so you have to use the codecs module.
There's also the matter of stuff that is supposedly ported but isn't completely. For example, Beautiful Soup works nicely under py3, but it doesn't have a typeshed entry so its import needs a special annotation to stop mypy from complaining about it.
The real loss with Python 3 is that it could have been so much better than it is. I remember hearing that Go expected to pick up a lot of migrating C++ users, but it got migrating Python users instead.
Here's a pain story about a 2 to 3 migration though:
https://dropbox.tech/application/how-we-rolled-out-one-of-th...
In fact, it's a perfectly viable strat in python to have several processes, each having several threads, each having an event loop.
And it will still be so, once this comes out. You will certainly use threads more, and processes less, but replacing 1000000 coroutines by 1000000 system threads is not necessarily the right strategy for your task. See nginx vs apache.
I really don't care that much which of them survive, I just want to rely on less of them
With that said, sure, threads and asyncio are complimentary in the sense that you can run tasks on threadpool executors and treat them as if they were coroutines on an event loop. But that serves no purpose unless you're trying to do blocking IO without blocking your whole process.
I have used Trio in real projects and I thoroughly recommend it.
This blog post [2] by the creator of Trio explains some of the benefits of those libraries in a very readable way.
[1] https://trio.readthedocs.io/en/stable/
[2] https://vorpus.org/blog/some-thoughts-on-asynchronous-api-de...
But yes, consider alternatives before you pick asyncio as your approach!
Talk: https://www.youtube.com/watch?v=oLkfnc_UMcE
Blog post: https://vorpus.org/blog/notes-on-structured-concurrency-or-g...
And since we are stuck with colored functions in python, the choice of stack matters very much.
Now, if you want easier concurrency, and a solution to a lot of concurrency problems that curio solves, while still being compatible with asyncio, use anyio:
https://anyio.readthedocs.io/en/stable/
It's a layer that works on top of asyncio, so it's compatible with all of it. But it features the nursery concept from Trio, which makes async programming so much simpler and safer.
JavaScript doesn't need a GIL because it doesn't really have threads. WebWorkers are more akin to multiprocessing than threads in Python. Objects cannot be shared directly across WebWorkers so transferring data comes with the expense of serializing/deserializing at the boundary.
It isn't anymore.
In [3]: from asyncio import run
In [4]: async def async_func(): print('Ran async_func()')
In [5]: run(async_func())
Ran async_func()
Top-level async/await is also available in the Python REPL and IPython, and there are discussions on the Python mailing list about making top-level async/await the default for Python[1]. In [1]: async def async_func(): print('Ran async_func()')
In [2]: await async_func()
Ran async_func()
[1] https://groups.google.com/g/python-ideas/c/PN1_j7Md4j0/m/0xy...Not sure it will get there, but it would be nice. I think putting a top level "await" is explicit enough for stating you want an event loop anyway.
Now, with TaskGroup in 3.11, things are going to get pretty nice, espacially if this top level await plays out, provided they include async for and async with in the mix.
Now, if they could just make so that coroutines are automatically schedules to the nearest task group, we would almost have something usable.
- The event loop in JS is invisible and implicit. V8 proved it can be done without paying a cost for it, and in fact most real life python projects are using uvloop because it's faster than asyncio default loop. JS dev don't think of the loop at all, because it's always been there. They don't have to chose a loop, or thinking about its lifecycle or scheduling. The API doesn't show the loop at all.
- Asynchronous functions in JS are scheduled automatically. On python, calling a coroutine function does...nothing. You have to either await it, or pass it to something like asyncio.create_task(). The later is not only verbose, it's not intuitive.
- Async JS functions can be called from sync functions transparently. It just returns a Promise after all, and you can use good old callbacks. Instantiating a Python coroutine does... nothing as we said. You need to schedule it AND await it. If you don't, it may or may not be executed. Which is why asyncio.gather() and co are to be used in python. Most people don't know that, and even if you know, it's verbose, and you can forget. All that, again, because using the event loop must be explicit. That's one thing TaskGroup from trio will help with in the next Python versions...
- the early asyncio API sucked. The new one is ok, asyncio.run() and create_task() with implicit loop is a huge improvement. But you better use 3.7 at least. And you have to think about all the options for awaiting: https://stackoverflow.com/questions/42231161/asyncio-gather-...
- asyncio tutorials and docs are not great, people have no idea how to use it. Since it's more complex, it compounds.
E.G, if you use await:
With node v14.8+:
await async_func(params)
With python 3.7+: import asyncio
async def main():
# no top level await, it must happen in a loop
await async_func(params)
asyncio.run(main) # explicit loop, but easy one thanks to 3.7
E.G, deep inside functions calls, but no await:With node:
...
async_func(params)
With python 3.7+: ...
# async_func(params) alone would do nothing
res = asyncio.create_task(async_func(params))
...
# you MAY get away with not using gather() or wait()
# but you also may get "coroutine is never awaited"
# RuntimeWarning: coroutine 'async_func' was never awaited
asyncio.gather(res)
Of course, you could use "run_until_complete()", but then you would be blocking. Which is just not possible in JS, there is one way to do it, and it's always non blocking and easy. Ironic, isn't it? Beside, which Python dev knows all this? I'm guessing most readers of this post will have heard of it for the first time.Python is my favorite language, and I can live with the explicit loop, but explicit scheduling is ridiculous. Just run the damn coroutine, I'm not instantiating it for the beauty of it. If I want a lazy construct, I can always make a factory.
Now, thanks to the trio nursery concept, we will get TaskGroup in the next release (also you can already use them with anyio):
async with asyncio.TaskGroup() as tg:
tg.start_soon(async_func, params)
Which, while still verbose, is way better:- no gather or wait. Schedule it, it will run or be cleaned up.
- no need to chose an awaiting strat, or learn about a 1000 things. This works for every cases. Wanna use it in a sync call ? Pass the tg reference in it.
- lifecycle is cleanly scoped, a real problem with a lot of async code (including in JS, where it doesn't have a clean solution)
You can't "just run the damn coroutine", that's not what coroutines are.
But that does point to the mistake of Python, at least from a UX perspective: coroutines are more efficient but they're also a lot more prone to use errors, especially in dynamically typed languages. Async functions should probably just have been tasks, which is what they are in JS.
Well it has queues and threads already.
Its just that asyncio for socket handling at least (in the testing that I did) is about 5% faster. (one asyncio socket "server" vs ten threads [with a number of ways to monitor for new connections])
I always assumed that people wanted asyncio because they look at javascript and thought "hey I want GOTOs cosplaying as a fun paradigm"
Check out anyio if you want to use them now.
If you want to use structured concurrency now, IMO the best bet is to use Trio directly. Reading posts by the author makes it clear that every detail of the library had been extremely scrutinised, not just the API (e.g. see this long post on ctrl-C handling [3], or any number of long technical discussions on the issue tracker), so I think it's a better choice in any case.
[1] https://twitter.com/1st1/status/1041855365745455104
[2] https://docs.python.org/3.11/whatsnew/3.11.html
[3] https://vorpus.org/blog/control-c-handling-in-python-and-tri...
I totally disagree with this negative perspective of asyncio.
async programming is MUCH easier to program and understand than other concurrency solutions like multithreading.
async works extremely well as a programming model as evidenced by the fact that it's exactly the model being adopted by all languages that want to implement practical and developer friendly concurrency.
When I read such a negative take on asyncio I assume only this is a developer who hasn't done alot of programming with it, and is therefore still somewhat lacking in full understanding.
If you do anything on the CPU or if you have any I/O which is not async you stall the event loop and everything grinds to a halt.
Imagine a program which needs to send heartbeats or data to a server in a short interval to show liveness, Kafka for example. Asyncio alone can't reliably do this, you need to take great care to not stall the event loop. You only have exactly one CPU core to work with, if you do work on the CPU you stall the event loop.
We see web frameworks built on asyncio but even simple API only applications constantly need to serialize data which is CPU-bound. These frameworks make no effort (and asyncio doesn't give us any tools) to protect the event loop from getting stalled by your code. They work great in simple benchmarks and for a few types of applications but you have to know the limits. And I feel that the general public does not know the limitations of asyncio, it wasn't made for building web frameworks on the async event loop. It was made for communicating with external services like databases and calling APIs.
But that's always going to be the case for single threaded code. If you're ready to use threads, then that integrates pretty seamlessly with asyncio by using an executor task.
> asyncio doesn't give us any tools to protect the event loop from getting stalled by your code
Again, check out executors: https://docs.python.org/3/library/asyncio-eventloop.html#asy...
Asyncio in Python and JS are very different beasts.
All those frameworks trade off high performance if everything is well behaved against easy of use and potential of very bad performance if some regression is introduced.
Whether that tradeoff ia a good one to take will depend on the application.
For nearly every popular library there is now a (usually inferior, less robust) async one. The benefits of Linus' Law are reduced.
Watch the very NSFW (lots of swearing) but hysterically funny video "node.js is bad ass rock star tech" on youtube sometime ;). https://www.youtube.com/watch?v=bzkRVzciAZg
This is almost always the case of async tasks disappearing into the void. After shooting myself in the foot with this one time to many I have a hard rule to never use create_task. Instead make sure every single task ends up in some kind of gather() or wait() awaited from the top level. This will ensure any exceptions are propagated. If the number of tasks are dynamically created, while others are still ongoing, add them to a common list and restart your wait() call.
IMO the reason that we have so many ways of doing concurrency in Python (fra asyncio, curio, trio to gevent, multiprocessing etc.) is that it was never properly dealt with.
It has to be built into the language, a feature of the language, like fx. garbage collection. The model of Pony or Erland, where are execution thread is started per core could also have been used in python, instead we got the async/await mess, which almost created a whole new language, where every library has to be rewritten.
It saddens me to think that the ugly cludge that async/await is got added to Python almost without any discussion, whereas the insignificant walrus operator got so much heat that GVR quit.
—————
"… but I'll give a few more examples specific to this project of ideas (or code) taken from other communities:
- Biased reference counting (originally implemented for Swift)
- mimalloc (originally developed for Koka and Lean)
- The design of the internal locks is taken from WebKit (https://webkit.org/blog/6161/locking-in-webkit/)
- The collection thread-safety adapts some code from FreeBSD (https://github.com/colesbury/nogil/blob/nogil/Python/qsbr.c)
- The interpreter took ideas from LuaJIT and V8's ignition interpreter (the register-accumulator model from ignition, fast function calls and other perf ideas from LuaJIT)
- The stop-the-world implementation is influenced by Go's design (https://github.com/golang/go/blob/fad4a16fd43f6a72b6917eff65... )"
(Tulloch is the best hacker and mathematician I’ve worked with in a 20 year career).
> The interpreter's memory allocator has been replaced with mimalloc
These are very similar ideas!
Mimalloc is notable for its use of separate local and remote free lists, where objects that are being freed from a different thread than the page’s heap’s owner are placed in a separate queue. The local free list is (IIRC) non-atomic until it is empty and local allocs start pulling from the remote queue.
The general idea is clearly lazy support for concurrency, matching up perfectly with Python’s need to keep any single threaded perf it has. I’m impressed with the application of all of these things at once.
I will be glad if the GIL is fixed but I think people reach for threads too quickly and too often.
Yeah of course, except when you use multiprocessing to do some CPU-intensive work and one of the subprocess get OOMKilled. Now your main process just hang forever. This was reported on bpo roughly 10 years ago and the response is "we can't fix this".
Is this enough to convince you multiple processes sometimes lead to unnecessary complexity?
Yeah... could phrase this as "All programs written with the assumption of a GIL are now broken" instead. Wish they had done this as part of the breaking changes for python 3, I guess they'll have to wait for Python 4 for this?
C extensions can already start as many threads as they like. Threaded pure Python, even if GIL-less, is still slow, so what is the point?
The whole point of Python (before asyncio, pattern matching etc.) was being simple and having a nice C interface. If that continues to erode, people will (and should) look at other languages. C++ for example is pretty Pythonic these days, Java does not have these problems, Erlang (while slow) was written for concurrency from scratch, etc.
I agree though — it’s tempting to keep extending and stretching the language to be something it was never designed for; but at some point it’s been stretched so far it loses the properties that made it attractive to start with. I like Python, but some of the things people are using it for now, they should really consider another language instead, and write a Python wrapper on top of that if they must use it from Python.
If I am building a project where concurrency or asynchrony are essential, am I going to choose Python? If I need to bolt these on to an existing project to meet a deadline, how much runway do I really get from these enhancements before I hit the limitations of the language, and need a new tool anyway?
I love Python, and use it a great deal, but I’ve not seen anything in my experience to assuage these doubts. Happy to be convinced otherwise, though. I’m sure there are circumstances I haven’t thought of.
Like many data processing & data science jobs. Also anything doing disk IO, network IO, etc. Or anything running on a machine with multiple cores (i.e. almost any machine these days). So, the sweet spot would be running data jobs running on multi core machines doing things with files and accessing things over a network. That sounds a lot like a core use case for Python.
Python works around this by using processes and outsourcing all the pesky difficult stuff to native components. It kind of works, hence the popularity but it does add a few layers of complexity and it is needlessly slow.
It seems the biggest blocker for removing the Gil has simply been the python community itself having talked themselves into this being hard/undesirable and resisting change.
This little quote in the article is a great example of this:
> as Guido van Rossum noted, the Python developers could always just take the performance improvements without the concurrency work and be even faster yet.
IMO most of the additions to Python in the past decade haven’t been aimed at people choosing a language, but at people working on large existing Python codebases who have too much inertia to change languages.
The cause of this is that the people in charge of language design (first Guido at Dropbox and now members of the Steering Council) are in exactly that situation.
The effect is that Python has lost focus on what it was originally good for (executable pseudocode for scripting) in favour of adding mediocre support for concurrency, static typing, and now pattern matching.
For some reason people seem to think that since Python code is easy to read, that it's a "scripting language" (whatever that means). There are a lot of use cases for a language that's easy to do easy things in, and where performance doesn't really matter (or can be sorted out later.
At the most basic level you only need to put the logic into a function. Of course, the cost of that adjustment may vary, so more options are good. If Python becomes easier to use in this respect then everyone wins.
That said, I am also always interested in GIL-related content like this! Loved the article.
It's a powerful assumption for both python code and extensions to be able to make that only one thread will be executing in the interpreter at a time. Knowing it, you can do a lot of things with a much lower cognitive burden. I tend to think through a problem initially in a non-concurrent way and then think "ok, but there's concurrency to think of too, so how is this all affected?". With the GIL you usually don't need to go far into that if at all, and that's useful.
That doesn't mean I don't approve of concurrency. I use lots of languages, and a need for proper concurrency is one of the major reasons I might avoid python as a tool for a particular task.
But there are lots of languages, and python became the popular tool it is with the GIL. If python were to embrace concurrency in the interpreter its nature would change, and I think my toolbox would lose something valuable.
That said, I'm not worried. CPython exists in a cloud of extensions developed against its C API, and these are heavily reliant on the GIL. Refcounting isn't even the start of the problems you would need to solve in order to remove it and not have everyone just move to a fork that still has it. I'll be astonished if anyone manages to pull it off.
You often don't even need to do this yourself. GNU parallel is the way to go for dividing work up amongst CPU cores. Why reinvent the wheel?
I agree with you that threads are talked about way more than they should be. It's like all programmers learn this one simple rule: to be fast you have to be multi-threaded. It's really not the case. There is also massive confusion amongst programmers on the difference between concurrency and parallelism. I sometimes ask applicants to describe the difference and few can. Python is fine at concurrency if that's all you want to do.
Because most problems are not the embarrassingly parallel kind suitable for use with GNU parallel. For example, any problems that require some communication between the individual tasks.
We’re not talking about writing scripts to run on your laptop. We’re talking about code written for production applications. Deploying GNU parallel to production nodes / containers would be a major change to production systems that may not be feasible and even if it is would come with a high cost in terms of added complexity, maintenance, and production troubleshooting.
Python is notably very popular in two communities: web developer and scientific computing.
The former usually yell loudly every time someone propose to remove GIL. Meanwhile everyone in the scientific computing community had to learn how to workaround GIL which absolutely sucks and sometimes just impossible. (e.g. I have a mostly memory-bandwidth-bound data loading pipeline but it sometimes need multiple cores for doing some trivial data transformation with numpy. This is impossible to do efficiently in Python right now, due to GIL)
Do you mean Python is not the right tool for my job and we should drop numpy/scipy/... and let Python be your shit tool for rendering web pages?
Also, IMO Python is the right tool for glueing optimized C++ implementation of various linalg algos together. And this is exactly how we use Python. And we still have to workaround GIL. Yes, it is that bad.
<rant> Glue codes could be slow, but they must scale. They should not unnecessarily contend for a stupid lock. GIL is really a scalability bug and I do acknowledge it is a hard-to-fix one due to the world's legacy codebases depends on it. However when someone applies an absurd amount of computer science (the design OP posted is literally based on state-of-the-art PL research), you should at least be sincerely curious why people are being so serious about it. </rant>
Most of Python codes depend on subtle details of CPython internal. For example sometimes it is just convenient to assume GIL exists (i.e. simplifies concurrency codes because "you know there are at most one thread running").
Python is the tool I pick for quick scripting, not for highly performant systems - there are languages and run times for that.
Sometime highly productive software does not need to be highly performant, and that does not make the software any more or less valuable. And sometimes speed of iteration is more valuable than speed of run time execution.
Fair.
> or any more performant than it already is.
Well, you can certainly argue that you’d prefer that the effort devoted to performance could be better spent elsewhere, but it seems a little down to say you don’t think it should be faster.
Let’s not beat around the bush here: pure python is orders of magnitude slower than other similar tier languages, eg. javascript.
That’s because it’s never been a priority.
It also keeps getting new features.
You can’t keep adding new features to anything without it getting slower bloating and becoming sluggish unless you devote effort to keeping things fast.
So, I certainly have no problems with people working on making it faster.
That’s awesome.
The goal isn’t “pure python only, no more c!”
It’s just: stop the pure python code being such a major bottleneck.
But if Python continues as is, it will continue to to lose major enterprise traction as web companies transition to using faster languages for applications and infrastructure. It'll be tough to stave off the negative feedback loop at that point.
I'm not saying Python shouldn't improve. But, if it comes to it, Python shouldn't cannibalize the niche it filled to do so. That will just spark other languages to fill the niche again.
It’s too late for that, IMO. Python’s already added async-await because it wants to be C#, type hints because it wants to be Java, and pattern matching because it wants to be Haskell.
People who liked Python because of what made it different from other languages have long since been left behind.
Also, making threading better is not necessarily a new feature if done well - it could be mostly transparent to users.
Many high-throughput, high-concurrency systems run on Python, famously including Instagram and Pinterest (which see quite a lot of traffic).
Unless you really are doing greenfield development in an isolated application, these considerations often trump any language feature.
Because sometimes what you really need, or at least want, is an overlap of concurrency and other things, and Python is optimal for you for the other things.
If you just need concurrency, sure, but how often is that the only requirement?
Very few people set out going asking themselves about such low level details on day one of a project. Especially something that was an MVP or POC
The answer historically has been c/c++ and bind to python. This work is mainly motivated by one of those libraries wanting to write less c++ bindings and be able to do operations like these parallel directly in python.
Specific to your point, recruiting for Elixir talent is a problem compared to more mainstream languages. Recruiting in general is extremely hard at this moment.
If you’re sure you won’t be needing a lot of memory and the program will be short lived that could be a large speed up and you could skip the Gil.
Or worse, you end up with the async schism all over again, with new "threadless" versions of popular libraries springing up.
> Whenever the owning thread drops a reference to an object, it checks both reference counts against zero. If both the local and the shared count are zero, the object can be freed, since no other references exist. If the local count is zero but the shared count is not, []a special bit is set to indicate that the owning thread has dropped the object[]; any subsequent decrements of the shared count will then free the object if that count goes to zero.
This seems... off. Wouldn't it work better for the owning thread to hold (exactly) one atomic reference, which is released (using the same decref code as other threads) when the local reference count goes to zero?
Edit: I probably should have explicitly noted that, as jetrink points out, the object is initialized with a atomic refcount of one (the "local refcount is nonzero" reference), and destroyed when the atomic refcount is one and to-be-decremented, so a purely local object never has atomic writes.
The only atomic operation is during destruction: the local reference count is decremented non-atomically, and then if it is zero, we need an atomic memory_order_release decrement for the remote reference count.
Actually, we don't. We need a atomic load, but if the results of that load indicate that we're destroying the last reference to the object (which does need to be more complicated than just a extra remote reference; see [0] and [1]), we can just destroy the object as-is without actually doing a atomic store, because by definition there is no reference to the object through which another thread could inspect the remote refcount. (If there was, our reference wouldn't be the last one.)
0: https://news.ycombinator.com/item?id=28883218
1: https://sci-hub.se/https://dl.acm.org/doi/10.1145/3243176.32...
This way, if an object is created in one thread and transferred to another, the other thread wouldn't even need to do a lot of atomic reference count manipulations. There wouldn't be surprising behavior in which different threads run the same code with different speed, just by virtue of whether they created the objects or not.
With the proposed scheme, there are two counters (and, i assume, the ID of the owning thread), so a small fixed-size structure, which can sit directly in the object header. With your scheme, you need a variable and unbounded number of counters. Where would they go?
(I may misunderstand your remark, as ‘releasing’ is a bit ambiguous. It could mean decreasing reference count and freeing the memory if the count goes to zero or just plain freeing the memory)
The local ref count can go to zero while other threads still have references to the object (e.g. when the allocating thread sends an object as a message to another thread and, knowing the message arrived, releases it), so freeing the memory when it does would be a serious bug.
Also, the shared ref count can go negative. From the paper:
> As an example, consider two threads T1 and T2. Thread T1 creates an object and sets itself as the owner of it. It points a global pointer to the object, setting the biased counter to one. Then, T2 overwrites the global pointer, decrementing the shared counter of the object. As a result, the shared counter becomes negative.
That can’t happen with the biased counter because, when it would end up going negative, the object gets unbiased, and the shared counter gets decreased instead.
That asymmetry is what ensures that only a single thread updates the biased counter, so that no locks are needed to do that.
The reference is released; ie the (atomic) reference count is decremented (and the object is only freed if that caused the atomic reference count to go to zero).
> From the paper
I missed that there was a paper and was referring to the proposed implementation in python that was described in TFA. IIUC, biased refcount (in paper) is local (in my description), and shared is atomic, correct?
> the shared ref count can go negative
And that makes sense. Thanks. (And also explains how to deal with references added by one thread and removed by another, when one of those threads is the object owner.)
> The simplest change would be to replace non-atomic reference count operations with their atomic equivalents. However, atomic instructions are more expensive than their non-atomic counterparts. Replacing Py_INCREF and Py_DECREF with atomic variants would result in a 60% average slowdown on the pyperformance benchmark suite.
Nope, my proposal still uses two reference counts (one atomic, one local); it just avoids having a seperate flag bit to indicate that the owning thread is done.
The meaning of the extra bit is "the object doesn't have an owning thread anymore, and the local refcount will always be zero; and the shared refcount cannot go negative anymore so a zero really means the object can be freed".
A second bit is used if a non-owning thread notices local+shared=0. In that case the object is placed on a list that the owning thread will go through every now and then. For all objects in the list, the owning thread transfers the local references to the shared refcount, disowns the object (by setting the first special bit). Then, according to the rules for the first social bit, if the resulting shared refcount is still zero the object can be freed.
I'm digging the 2 reference counters, that makes sense to me, but I don't know why it isn't something more like:
"every time a new thread takes a reference, atomic +1, every time a new thread's local count hits 0, atomic -1. If the shared reference is 0, free".
IDK what special purpose the flags are serving here.
Any other thread can't know if it's the first time or not it's taking a reference to an object.
I think you're under the impression that the refcount would only ever need to be incremented if the object was shared to another thread, but that's not the case. The refcount isn't a count of how many threads have a reference to the object; it's a count of how many objects and closures have a reference to the object. Even objects that never leave their creator thread will be likely to have their reference count incremented and decremented a few times over their life.
I think you're under the impression that there's only one refcount. The point of the original design (and this one) is that there are two refcounts: one that's updated only by the thread that created the object, and therefor doesn't need to use slow atomic accesses, and one that's updated atomically, and therefor can be adjusted by arbitrary threads.
Then thread B clears the global variable. With your scheme the local refcount would be 1 but the shared refcount would be 0, so thread B would destroy the object even though it's referenced by thread A.
EDIT: never mind the question, I just read that the special bit is atomic.
0: https://sci-hub.se/https://dl.acm.org/doi/10.1145/3243176.32...
1: https://news.ycombinator.com/item?id=28883218 (seriously, upvote this; it should be higher in the list of responses, since it actually properly refutes my original comment)
> Whenever the owning thread drops a reference to an object, it checks both reference counts against zero. If both the local and the shared count are zero, the object can be freed, since no other references exist. If the local count is zero but the shared count is not, a special bit is set to indicate that the owning thread has dropped the object; any subsequent decrements of the shared count will then free the object if that count goes to zero.
So in this program:
import threading
def produce():
global global_foo
local_foo = "potato"
global_foo = local_foo
def consume():
global global_foo
local_foo = global_foo
global_foo = None
if __name__ == '__main__':
produce()
thread = threading.Thread(target=consume)
thread.start()
thread.join()
What happens to the counts on the string "potato"?In produce, the main thread creates it and puts it in a local, and increments the local count. It assigns it to a global, and increments the local count. It then drops the local when produce returns, and decrements the local count. In consume, the second thread copies the global to a local, and increments the shared count. It clears out the global, and decrements the shared count. It then drops the local when consume returns, and decrements the shared count.
That leaves the local count at 1 and the shared count at -1!
You might think that there must be special handling around globals, but that doesn't fix it. Wrap the string in a perfectly ordinary list, and put the list in the global, and you have the same problem.
I imagine this is explained in the paper by Choi et al, but i have not read it!
> When the shared counter for an object becomes negative for the first time, the non-owner thread updating the counter also sets the object’s Queued flag. In addition, it puts the object in a linked list belonging to the object’s owner thread called QueuedObjects. Without any special action, this object would leak. This is because, even after all the references to the object are removed, the biased counter will not reach zero — since the shared counter is negative. As a result, the owner would trigger neither a counter merge nor a potential subsequent object deallocation.
> To handle this case, BRC provides a path for the owner thread to explicitly merge the counters called the ExplicitMerge operation. Specifically, each thread has its own thread-safe QueuedObjects list. The thread owns the objects in the list. At regular intervals, a thread examines its list. For each queued object, the thread merges the object’s counters by accumulating the biased counter into the shared counter. If the sum is zero, the thread deallocates the object. Otherwise, the thread unbiases the object, and sets the Merged flag. Then, when a thread sets the shared counter to zero, it will deallocate the object. Overall, as shown in invariant I4, an owner only gives up ownership when it merges the counters.
Well, that works, but it's a bit naff.
import threading
def produce():
global global_foo
local_foo = "potato"
global_foo = local_foo
def consume():
global global_foo
local_foo = global_foo
global_foo = None
if __name__ == '__main__':
produce()
thread = threading.Thread(target=consume)
thread.start()
thread.join()If you follow this reasoning, the operations above result in local=0/shared=0 after the last assignment.
The algorithm from the paper you posted in another comment indeed looks more complicated than it needs to be and prone to bad performance.
Judging by the design, it appears they were trying to avoid the local thread to touch the shared counter in any circumstance on the hot path, but I wonder if it would not be much simpler for the owner thread to just check a flag set by the non-owner thread and perform the unbiasing/freeing right away without going through all the queuing mechanism.
I moved into the language full-time in 2010 and it's now 2021.
The packaging ecosystem is still a burning dumpster fire, the performance is still hot garbage and the whole approach to asyncio makes me want to bang my head against a wall.
Tthe latest additions in Python 3.10 have me shaking my head. I love pattern matching (Yes, Scala fanboy detected) but shoving them into Python just seems....poorly thought out.
I really hope to move away from the language in the long-term because I feel like it's a bad thing when I would rather work in Java or C++ than Python. For me it feels like Java and C++ took a look at themselves at the end of the 2000s and said "Okay, we need to sort something out, what we're doing now is not winning any hearts" while Python did also did some introspection and decided "Meh, let's just keep throwing mud at the wall until something sticks". It's one of the few languages I've worked with which seems to be actively getting worse every year, which is kinda sad :-/
Like the syntax is... divisive. And there's stuff like Black not being able to work with 3.10 for a while cuz it needs to rewrite its parser. But Python 2 -> 3 was a mess, and the python maintainers learned their lesson by making changes that would improve existing code without having to do full rewrites.
Like if you scroll through the changelog of recent releases you'll find loads of QoL improvements and things that are actually making the language more portable and easier to use in production. The CPython team does listen to needs of people (at least when it goes beyond aesthetics concerns...)
These issues, plus the inability to build a standalone binary, are why many Python programmers have adopted Go. Other than maybe packaging, Go gets all these things right. It’s just a shame that the language itself isn’t as nice as Python.
One of us, one of us, one of us!
I guess years of Python has spoiled me.
> ... the first of which is called "biased reference counts" ... With this scheme, the reference count in each object is split in two, with one "local" count for the owner (creator) of the object and a shared count for all other threads. Since the owner has exclusive access to its count, increments and decrements can be done with fast, non-atomic instructions. Any other thread accessing the object will use atomic operations on the shared reference count.
So if the owner needs to check the shared ref count every time it changes the count of the non-atomic local count, isn't that basically all the negatives of a single shared atomic counter?
Every design has pros and cons. Of course the GIL has well-known costs but it also has benefits. It makes developing C modules that integrate into Python relatively safe and trivial. And this is where Python shines: as plumbing where CPU intensive work (which is still single-threaded) is done by C modules. This is how the likes of Mercurial, Jupyter, numpy and scipy. And probably PyTorch but I know less about that.
My personal view is that the world has largely moved on from dynamically typed languages for anything non-trivial or that isn't essentially plumbing. For good reason. Of course people will bring up Javascript but it has a captive market as being the only thing that'll universally run code in a browser and the likes of TypeScript can ease that burden anyway.
This just feels fighting the seemingly inevitable fate of Python.
This is not correct. There is a lot of data analysis code in the research and scientific community written in python. A lot of PyCon attendees and speakers come from these communities. Oftentimes, it’s not easy to write code to perform a task entirely in numpy, and then you incur massive slowdowns (often 20-100x). This is a common and contemporary problem in the python ecosystem.
GVR initially didn’t think that python needed to be faster either, but recently changed his mind. You can find a presentation on his motivations here: https://github.com/faster-cpython/ideas/blob/main/FasterCPyt...
Sam Gross comes out of that community so he’s familiar with the motivations for making raw python faster.
I would be very happy with that, together with a 10% speed increase in single-threaded performance that they said would come as a result of these changes.
I think the owner only needs to check the shared count when it changes the local count to zero, not every time it changes the local count.
Which is what, exactly? If you’re suggesting that devs will lose interest in Python then you’re simply not paying attention. Python is _gaining_ in popularity, over Java, C, even JS. It’s not that control over typing isn’t an issue, but developers are undeterred.
It does not, it only needs to check the shared refcount when the local count reaches 0, to decide whether it can free the object immediately or whether it should mark it as "unowned".
I have no idea if this is the reason in this particular in case, but on most architectures if you can fit everything you need to atomically modify together into one word there will be an instruction to do that quickly.
For example many architectures have a compare-and-swap instruction. That generally takes 3 arguments: a memory address, an old value, and a new value. It atomically compares the word at the given address to the old value, and if and only if they are the same writes the new value to the memory address.
Multiprocessing sort of works but it’s really sucky.
It feels quite heavy and clunky, is my issue.
By the way, concurrent.futures in Python provides identical (almost) features for a process and thread pool executor, so either choice there can be handled the same way. I'm most fond of the executor.map() method for very easy parallelization of work-loops.
My understanding was that CPython viewed any single-threaded performance regression as a blocker to GIL-removal attempts, regardless of if other work by the developer has sped up the interpreter? This article seems to somewhat gloss over that with "it's only small". I'd be interested in knowing other estimations of what the "better-than-average chance" of this (promising sounding) attempt were.
Breaking C extensions (especially the less-conforming ones, which seem likely to be the least maintained) also seems like it would be a very hard pill to swallow, and the sort of thing that might make it a Python 3-to-4 breaking change, which I imagine would also be approached extremely carefully given there are still people to-this-day who believe that python 3 is a mistake and one day everyone will realise it and go back to python 2 (yes, really).
Previous GILectomy attempts incurred significant single-threaded performance penalties, on on the order of 50% or above. If Gross's work yields low single-digit performance penalty it's pretty likely to be accepted as this is the sort of impacts which can happen semi-routinely as part of interpreter updates.
The complete breakage of C extensions would be a much bigger issue.
And on top of that, Guido has retired now, and the steering committee may feel differently as long as the spirit of the restrictions is upheld.
> Gross has also put some significant work into improving the performance of the CPython interpreter in general. This was done to address the concern that has blocked GIL-removal work in the past: the performance impact on single-threaded code. The end result is that the new interpreter is 10% faster than CPython 3.9 for single-threaded programs.
A hard pill to swallow.. ain't that bad if it also benefits you tremendously, which fixing the GIL would do.
No? Why would we think that? There are people who willingly use java; compared to that the problems with python 3 are downright non-obvious as long as you never need to work with things like non-Unicode text.
My guess is that this was done for memory efficiency, but is there really no way to have the local refcount be a packed struct or something, where the "count" field holds the real ref count and the flags are stored separately? I have no understanding of the CPython internals, so it may very well be impossible, but I would appreciate someone explaining why.
Was going to say do the opposite. Set the bit if you want counting and then modify the increment and decrement to add or subtract the bit, thereby eliminating condition checking and branching. But it sounds like the concern is cache behavior when the count is written. Checking the bit can avoid any modification at all.
So might as well do it in one shot.
But what im really interested in is - if this can be ported to Pypy. Given that pypy is already quite a bit faster than cpython...it would be interesting to see what the nogil will unleash
“My program has 2^64 references to an object, which caused it to become immortal”
=)
EDIT: there is a dockerfile in there https://raw.githubusercontent.com/colesbury/nogil/nogil/Dock...
Earmarks work, folks!
An opt-in for C libraries that are multi-threaded-aware could be useful as well. It would be a forcing function to ensure that libraries _eventually_ become MT-aware and eventually the older versions would drop away.
> "I'm not thrilled about the idea of Python 4 and nobody in the core dev team really is – so probably there never will be a 4.0 and we'll just keep numbering until 3.33, at least," he said in a video Q&A.
but also:
> Van Rossum didn't rule out the possibility of Python 4.0 entirely, though suggested this would likely only happen in the event of major changes to compatibility with C. "I could imagine that at some point we are forced to abandon certain binary or API compatibility for C extensions… If there was a significant incompatibility with C extensions without changing the language itself and if we were to be able to get rid of the GIL [global interpreter lock]; if one or both of those events were to happen, we probably would be forced to call it 4.0 because of the compatibility issues at the C extension level," he said.
I suspect you mean “PyPy” which is a very different thing than “pypi”.
I hope this new style of writing Python packages does not leak into the interpreter.
IIRC even PyPy and MicroPython use tracing GC.
Or, incredibly seasoned vets into their 50's and beyond.
tldr: you can use our 4-computer Dask cluster (including two GPUs, a GTX 1080Ti and a Radeon 6900XT) at no cost. If you need even more computing power, message me (george AT lindenhoney DOT com).
FAQ
What is Dask? Dask is a Python framework for distributed computing, designed to enable data scientists to process large amounts of data and huge computations on a scale from 1 to thousands of computers.
How do I use the cluster you created? Install Dask (python -m pip install "dask[complete]" from dask.distributed import Client client = Client(tcp://3.216.44.221:8786) Use it! https://examples.dask.org
Do I need to sign up? No. You can literally just use it as above from any Python script or notebook.
Why are you making it available? I’m looking to better understand how people use Dask and how to best make it available to data scientists as an easy to use service.
What can I use the cluster for? Anything you want such as data science, web crawling (except spam, porn, illegal activities or DoS) etc. Please be nice.
Can I hack your cluster? Probably not. But ff you find any security issues please let us know instead and we will fix them.
What’s the catch? Do you track my usage? None. These are my gaming/closet computers that I just want people to use. I do track anonymous function calls people make and the total volume of data that passes through the system (bandwidth, disk usage, RAM usage etc) but I do not look at or save any of your data.
How can I add my own worker machines to the cluster? Easy - set up Dask worker(s) and point them to tcp://3.216.44.221:8786
How about security and confidentiality? These are computers I have at home so all you have is my promise that I won’t look/save/copy your data or code. Pinky swear. However, it is possible for other unfriendly users to look at your data if you save it, even temporarily, on the disk, since all Dask tasks run under the same user.
Who are you? https://www.linkedin.com/in/georgeciobanunyc
What if someone else who uses the cluster messes up with my data, copies it or otherwise takes it down? Use your best judgement. I hardened the cluster’s security to the best of my ability but I can’t guarantee that someone else won’t mess with them. If you work for the NSA/a bank/IRS/etc you should definitely not upload sensitive data to these computers.
I need more GPUs or a bigger (hundreds or thousands of computers) cluster! Glad to help, just email me (see above).
I need a larger cluster but private (using AWS, Azure, GCP) Same as above, email me and I can help.
What are the computer specs? Two of them are AMD processors with 8 physical cores each, the other is a quad core Intel and the last one is a Mac (Intel, 4 cores). The dedicated graphics cards (GPUs) are on the AMD computers.
Multithreading in Python currently has the same limitation though but it needn't.
CPython is a naive interpreter, like original JavaScript. There's been progress since then.
This work is super exciting! Can pypy use the same recipe to offer true parallelism plus the jit??
Will be really interesting to see what pypy devs think of this work and how they might also lever it!
Sam's changes to CPython's container objects (dicts, lists), to make them thread safe might also be hard to port directly to Pypy. Pypy implements those objects differently.
It is a much less important release (for features) than 3.7, which for example added dataclasses and lots of typing and asyncio stuff.
The most significant change in 3.8 is a notoriously controversial new infix operator. Even it's supporters would say that it's a niche usecase.
> It is a much less important release (for features) than 3.7, which for example added dataclasses and lots of typing and asyncio stuff.
That's funny because my take is the exact opposite: dataclasses are not very useful (attrs exists and does more), deferred type annotations are meh, contextvars, breakpoint(), and module-level getattr/settattr but not exactly anything you can't do without.
Assignment expressions provide for great cleanups in some contexts (and avoiding redundant evaluations in e.g. comprehensions), expr= is tremendous for printf-debugging, posonly args is really useful, \N in regex can much improve their readability when relevant.
$dayjob has migrated to python 3.7 and there's really nothing I'm excited to use (possibly aside from doing weird things with breakpoint), whereas 3.8 would be a genuine improvement to my day-to-day enjoyment.
*: mostly true
This has been a problem for like 20 years and they have refused fixes before. And there have been fixes. They just don't see this as important
it's practically a religion that its a thing they wont change
"To be clear, Sam’s basic approach is a bit slower for single-threaded code, and he admits that. But to sweeten the pot he has also applied a bunch of unrelated speedups that make it faster in general, so that overall it’s always a win. But presumably we could upstream the latter easily, separately from the GIL-freeing part."
[1] https://mail.python.org/archives/list/python-dev@python.org/...
A lot of that is stuff that is enabled by, or was blocked pending, the new parser; I don't think it was blocked on Guido, and Guido haa hardly stopped being active and influential since stepping down as BDfL