7 ms·
Python’s Multiprocessing Performance Problem
- kobalsky 4y agoreplaced the print() for sys.stderr.write() to make it compatible with python2. the program still deadlocks on python3 but it works perfectly on python2, anyone know what changed between implementations that could be triggering this issue?
- itamarst 4y agoFrom memory, the reason it deadlocks is: 1. Writing to stderr grabs a lock. 2. Part of the multiprocessing code (perhaps not present in Python 2) also grabs this lock. 3. If you fork at the right moment (which is quite likely with the loop) the lock is held by a thread that is now dead, and so now you're waiting for a lock to release that will never be released.
- crabbone 4y agoI don't believe OP's deadlock is related to a rare event of dead thread holding a lock. The problem is that any calls to multiprocessing objects if not guarded by if __name__ == '__main__' will result in infinite loop / fork bomb kind of situation. For some reason on OP's computer that probably causes an appearance of the program hanging, but really, it will just crash after a while exhausting some resource.
- itamarst 4y agoIf I add a `if __name__ == '__main__':` I get the same result. Here's the gdb stack trace: #0 __futex_abstimed_wait_common64 (private=<optimized out>, cancel=true, abstime=0x0, op=393, expected=0, futex_word=0x17bc7c0) at ./nptl/futex-internal.c:57 #1 __futex_abstimed_wait_common (cancel=true, private=<optimized out>, abstime=0x0, clockid=0, expected=0, futex_word=0x17bc7c0) at ./nptl/futex-internal.c:87 #2 __GI___futex_abstimed_wait_cancelable64 (futex_word=futex_word@entry=0x17bc7c0, expected=expected@entry=0, clockid=clockid@entry=0, abstime=abstime@entry=0x0, private=<optimized out>) at ./nptl/futex-internal.c:139 #3 0x00007ff326c9cc5f in do_futex_wait (sem=sem@entry=0x17bc7c0, abstime=0x0, clockid=0) at ./nptl/sem_waitcommon.c:111 #4 0x00007ff326c9ccf8 in __new_sem_wait_slow64 (sem=0x17bc7c0, abstime=0x0, clockid=0) at ./nptl/sem_waitcommon.c:183 #5 0x00007ff326c9cd71 in __new_sem_wait (sem=<optimized out>) at ./nptl/sem_wait.c:42 #6 0x000000000042765b in PyThread_acquire_lock_timed (lock=0x17bc7c0, microseconds=-1, intr_flag=0) at ../Python/thread_pthread.h:483 #7 0x0000000000625813 in _enter_buffered_busy (self=0x7ff326f330f0) at ../Modules/_io/bufferedio.c:281 #8 0x000000000045f9b3 in buffered_flush (self=0x7ff326f330f0, args=<optimized out>) at ../Modules/_io/bufferedio.c:825 #9 0x0000000000524185 in method_vectorcall_NOARGS (func=func@entry=<method_descriptor at remote 0x7ff326f611d0>, args=args@entry=0x7fffa8bc7a38, nargsf=<optimized out>, kwnames=kwnames@entry=0x0) at ../Objects/descrobject.c:436 #10 0x000000000053bd5a in _PyObject_VectorcallTstate (kwnames=0x0, nargsf=<optimized out>, args=0x7fffa8bc7a38, callable=<method_descriptor at remote 0x7ff326f611d0>, tstate=0x17bf410) at ../Include/cpython/abstract.h:118 #11 PyObject_VectorcallMethod (name=<optimized out>, args=0x7fffa8bc7a38, nargsf=<optimized out>, kwnames=0x0) at ../Objects/call.c:828 #12 0x000000000060283a in _PyObject_CallMethodIdNoArgs (name=0x8f6120 <PyId_flush.lto_priv.2>, self=<optimized out>) at ../Include/cpython/abstract.h:243 #13 _io_TextIOWrapper_flush_impl (self=0x7ff326f40040) at ../Modules/_io/textio.c:3038 #14 _io_TextIOWrapper_flush (self=0x7ff326f40040, _unused_ignored=<optimized out>) at ../Modules/_io/clinic/textio.c.h:685
- crabbone 4y agoWell, it's hard for me to tell from this stack trace what's happening here. I don't recognize PyObject_VectorcallMethod. Is this a new thing? Last time I wrote any C code for Python I don't recall seeing / using this. Anyways, another common pitfall in multiprocessing is attempting to serialize multithreading / multiprocessing primitives s.a. locks, variables or mutexes. My memory may fail me, but, I think, it may result in deadlock too. I think, multiprocessing code tries to guard against it, but there are some weird rules for when it's OK for serialized objects to have those primitives (I think, initialization in __init__ is fine, but not so much otherwise or something like that), but the check isn't very good / just a heuristic... But, really, I don't remember this part well.
- JosephRedfern 4y agoThis post links to another post by the same author which goes into this in a little more detail: https://pythonspeed.com/articles/python-multiprocessing/ https://pythonspeed.com/articles/python-multiprocessing/
- crabbone 4y ago[flagged]
- ElectricalUnion 4y agoThere are only two kinds of languages: the ones people complain about and the ones nobody uses - Bjarne Stroustrup
- louwrentius 4y agoI don't know of a more appropriate quote, thank you.
- rdtsc 4y agoExactly. That's why OP suggested Erlang. I switched from Python to Erlang and never had issues with GIL or scaling or operability. Elixir shares the same BEAM VM so that's another option as well.
- Invictus0 4y agoI hate this quote. People still use things like floppy drives and fax machines in certain applications not because those devices are better but because of institutional inertia and bureaucracy. And the stuff we use isn't always the best thing out there, better products can still lose. Just look at Oracle.
- ElectricalUnion 4y ago> And the stuff we use isn't always the best thing out there, better products can still lose. Better products will lose, most of the time, unless they're significantly better as a product to a point were they can hurt and displace the incumbents. It's what people found out with Plan 9 vs UNIX.
- crabbone 4y agoIt's interesting that you decided to repeat this diatribe for the millionth time expecting... what effect exactly? Stroustrup licked every boot and inserted himself into every possible committee to promote his language until the network effect picked up. And later he post-rationalized about his language's popularity, attributing it to qualities the language never had. And you proceeded to conclude based on the diatribe you repeated that nobody should want good things, because everyone has to be satisfied with popular things, because you chose to eat garbage and you will be too jealous to see others getting better treats? ---- Yes. Python is garbage, and programmers should be actively discouraged from using it. Python is today in the hands of people both incapable and unwilling to improve the language in the aspects that matter, and that's why programmers need to try to defeat the network effect created by it instead of encouraging more complacency. It is pretty much in the same situation as C++, so, unintentionally, you sort of guessed the direction. Both languages started small and rode the popularity wave w/o actually filling the gaps in original design with the worthwhile contents. Kind of like a TV show that keeps capitalizing on its pilot, while not creating anymore engaging experience.
- xioxox 4y agoJust in case someone is interested, I've written a simple fork-based module for processing jobs for Python: https://github.com/jeremysanders/forkqueue https://github.com/jeremysanders/forkqueue This has the advantage of allowing work done inside a nested function, allowing large initial datasets to be shared and not have to be passed over pickle.
- itamarst 4y agoSee the article for an explanation of why this is a bad idea. Note that on macOS Python disabled fork()-based multiprocessing as the default long ago (Python 3.8?) because it's so broken, and it will stop being the default for multiprocessing on Linux in 3.14, deprecated in 3.12.
- xioxox 4y agoIt works really well if you avoid threads, and I've found it pretty easy to avoid them in my code.
- itamarst 4y agoYes, but... it's harder than one might think to avoid threads. Merely importing NumPy starts threads, for example.
- mickeyp 4y agoYes, and that's a good thing. Let numpy do its threading unless you know exactly why you don't want it to parallelise your matrix multiplications and what havbe you. Numpy releases the GIL so that works exactly as it should. Threads aren't bad: threads that cause resource contention with the GIL is (possibly) bad. That is almost always done explicitly by the developer and almost never done without your knowledge.
- itamarst 4y agoUnfortunately NumPy's thread pool is only for BLAS, the underlying library for numpy.linalg functions, mostly. Other operations are single-threaded. So you need your own thread pool (or process pool) if you want to parallelize anything else.
- whywhywhydude 4y agoUnless you are doing Machine learning or using numpy, I do not recommend anyone use python for anything performance sensitive. The problem is not just GIL. Because multithreading is not so common in python, it’s really hard to know if some external library is threadsafe. Python also supports async but a lot of libraries do not have asyncio compatibility, so you need to mix threads with asyncio which leads to a big mess.
- cgreerrun 4y ago> I do not recommend anyone use python for anything performance sensitive My default philosophy is to use python _until_ you find something that is performance sensitive, and then make a C/C++ extension for the slow bits. Pybind works great for a hybrid Python/C++ codebase (https://pybind11.readthedocs.io/en/stable/ https://pybind11.readthedocs.io/en/stable/). Then you can develop and prototype much quicker w/ Python but re-write the slow parts in C++. Definitely more of a judgement call when threading and function call overhead enter the equation, but I've found this hybrid "99% of the time Python, 1% C++ when needed" setup works great. And it's typically easier for me to eventually port mature code to C++/Go/etc once I've fleshed it out in Python and hit all the design snags.
- cgreerrun 4y agoIf you've never used Pybind before these pybind tests[1] and this repo[2] have good examples you can crib to get started (in addition to the docs). Once you handle passing/returning/creating the main data types (list, tuple, dict, set, numpy array) the first time, then it's mostly smooth sailing. Pybind offers a lot of functionality, but core "good parts" I've found useful are (a) use a numpy array in Python and pass it to a C++ method to work on, (b) pass your python data structure to pybind and then do work on it in C++ (some copy overhead), and (c) Make a class/struct in C++ and expose it to Python (so no copying overhead and you can create nice cache-aware structs, etc.). [1] https://github.com/pybind/pybind11/blob/master/tests/test_pytypes.cpp https://github.com/pybind/pybind11/blob/master/tests/test_py... [2] https://gitlab.unistra.fr/benzerara/pybind11/-/tree/master/example https://gitlab.unistra.fr/benzerara/pybind11/-/tree/master/e...
- sliken 4y agoI was working on a backup system, the usual. Walk a directory tree, track new/changed files, then queue them for sha256 and encryption, then upload to a server with gRPC. I hit the GIL, switched to multiprocessing, which helped. Still was about half as fast as I expected. Switched to go and using channels and got the performance I expected. Was still debating, till I got deeper into Python's crypto package. I ended up really happy with go.
- Animats 4y ago> happy with Go. Yes. I've used multiple threads in Python. It doesn't work well. Some packages, including cpickle, don't work right with multiple threads because they have static variables internally. It can work; I've had multi-threaded Python code running for years. But it's not a good approach for new work. Python does things the CPython naive interpreter can do easily, such as letting anything modify anything else. Any code anywhere can go find something far away in another thread in another module and mess with it. Everything is a dict, so that works. This makes other things hard. Pre-compilation is hard. Optimizing is hard. JIT is hard. Threading is hard. You can't nail down stuff that probably won't change, but might.
- dekhn 4y agoI believe the aws s3 command uses python multiprocessing and I've seen it saturate a 10gbit link so maybe you just didn't program it right?
- sliken 4y agoPossible. I had a fair amount of CPU going on, trying to keep 8 cores busy with SHA256(plaintext), encrypt, and SHA256(encrypted_blob). I was just trying to be straight forward, keep files queued, so that when a core went idle it could grab another. The go was similarly very straight forward, walktree -> CheckIfNewOrchanged -> channel -> sha256/encrypt/sha256. Channels made it really easy/clear and performed quite well. I was getting near linear scaling, CPU time consumed was 8x the wall clock, and speed increased 7.9x or so. With python I was getting significantly less performance per core and worse scaling. With 8 cores 10Gbit is 1.25GByte/8 = 160MB/sec which is ok, not great, depends on how much computation you are doing. My goal is keeping 100gbit saturated, but I am adding cores as well. I do hope to compare to Go vs Rust as well.
- oxfordmale 4y agoIf Python doesn't introduce multithreading before 2030, it will die a slow and painful death
- FlyingSnake 4y agoPython notwithstanding its certain limitations, will remain a mainstay language beyond 2030. It is a lucrative option in writing glue code, scripts, and almost all of data engineering and related fields depend on Python.
- oxfordmale 4y agoJava is still a mainstay language, despite its popularity slowly dropping for more than a decade. Python will be around for many years; however, now we have hit the end of Moore's law, the easiest way to speed up code is to multi-thread. I code exclusively in Python, so I can't judge if languages like Julia are serious contenders. I also agree that building up the same ecosystem as in Python will take some time, and therefore I do not predict a rapid decline. However, many of the things I use Python for can be easily done in another scripting language.
- skrtskrt 4y agoif other languages don't have equivalents for the devex/productivity enhancements of: * Django * FastAPI/Flask * Numpy/Pandas * PySpark * Jupyter Notebooks (gross I know but this is what "data analysts" and "ML/data engineers" use at many places) Then Python will stick around for forever. I would love if it the Go community would quit the "you don't need a framework, DUH it's GO" attitude. Make a Django/Rails for Go and there would be 10x the Go jobs.
- robswc 4y agoI've gotten into the "debate." People always suggest using anything but python but then provide no alternatives to the frameworks mentioned above. You _could_ certainly write it in Go. I write a lot of stuff in Go and I love it. I just don't want to recreate Django for the 100th time though, so I don't and I just use Python. By all means, if someone wants to write these frameworks, people will use them.
- VHRanger 4y agojoblib has been a decent solution to this issue: https://joblib.readthedocs.io/en/latest/ https://joblib.readthedocs.io/en/latest/ It doesn't manage to escape the python multiprocessing issue everywhere but it often does
- RobotToaster 4y agoWhy not use POSIX/SYS V message queues?
- while_true_ 4y agoI found it curious the author mentioned using the Multiprocessing with pickle() but not Pipe(). Pickle() streams entire objects, while Pipe() can be used to send data between processes. Maybe the latter is faster, especially if the data are short strings and the like?
- nijave 4y agoI think they mentioned pickling because that's what the multiprocessing queue uses by default. I think Pipe isn't necessarily a drop in replacement depending on the complexity of object you want to share but I have found it significantly faster for simple things.
- while_true_ 4y agoExactly. My assumption is Pipe() is faster for short and simple data because I assume it doesn't do the serialization conversion that Pickle does.
- nijave 4y agoYup, if you need to serialize a complex object manually before piping then you end up paying the price again (like this the multiprocessing Queue) I'm guessing that's part of the reason the article didn't mention it (it looks like they're talking about a Pandas DataFrame which I would say is non-trivial--compared to a primitive type) I'd think Pipe + Parquet should beat filesystem though. That really depends on storage I guess Iirc I played a bit with msgpack and orjson to see if there was anything to gain over Pickle but I don't think it made much difference. You'd probably need to deal with structs Looking at CPython source (3.10), on Windows, you always get a NamedPipe. On other platforms, you get a OS pipe when duplex=False otherwise a socket (socket.socketpair)
- GalaxySnail 4y agoHopefully PEP 684 [1] which suggests a per-interpreter GIL will improve the situation. [1] https://peps.python.org/pep-0684/ https://peps.python.org/pep-0684/
- sjatkins 4y agoGives me more reason to learn and use Julia. I have used python for years and love it in many ways but it certainly has warts.
- sjatkins 4y agoLeaving aside a moment the unexpected threaded fork issue mentioned I am thinking putting all the data to be shared among the processes into Redis would at least be a lot better than the clumsiness of pickling and unpickling.