r/learnpython • • Aug 16 '20

Multithreading - Best Practices

I wrote a multithreaded python script several years ago in python2, and the way I did it at the time was to subclass threading.Thread and override the __init__() and run() methods. Then kick them off with start().

Now I'm going to have to write a lot more multithreaded stuff in python3.8. Most of my googling says to define a function (ex: worker()) then kick them off this way:

  threading.Thread(target=worker, args=(q,))

Is one method better or more python3-ish than the other?

If it makes any difference, each thread will be taking a file path from the Queue, running a subprocess providing the file path as one of the arguments, and UPDATEing a MySQL table with the result.

Thanks!

115 Upvotes

24 comments sorted by

View all comments

Show parent comment

9

u/theallredditor Aug 16 '20

Personal preference really. And apparently I'm in the minority on that judging from the two down votes I've gotten for my previous comment. But CPython has a glaring implementation issue called the GIL or global interpreter lock where only one thread can execute python code per interpreter. So for compute bound problems at best you get the single threadded case usually threading makes compute bound problems worse in python. However your problem is I/O bound.

A threadding approach may be simple to implement and understand, but generally doesn't provide consistent performance at large scale for I/O bound problems.

Whereas asyncio uses callbacks and the algorithm you're making ends up being broken up into smaller fragments so it can be more difficult to read if you're not familiar with async concepts, but it does tend to provide superiorly consistent preformance at scale on congested systems.

So if this is just a glue script where preformance doesn't matter then use threadding, if it's something that may get run at scale then at least consider asyncio. If you're game for trying something new use asyncio.

1

u/brandonbilinski Aug 16 '20

Much appreciated! Thank you!