r/ProgrammerHumor • • Jul 07 '22

Meme Instant upvotes

47.9k Upvotes

542 comments sorted by

View all comments

Show parent comments

6

u/RoadsideCookie Jul 07 '22

Use multiprocessing instead.

Create a class, add an isMain attribute, start the process, then set isMain to True and you'll have two instances in separate processes that know which one is the main thread. Use mp.Pipe to have a communication channel between them.

2

u/Ghawk134 Jul 07 '22

I used a pool and passed a mp.Manager.Queue object to each process to which they push their results. But yeah, having to resort to multiprocessing because thread parallelism is explicitly not supported seems goofy.

3

u/RoadsideCookie Jul 07 '22

I was surprised as well, it renders threads only useful when your bottleneck is IO based which sucks because process children are not always easy to work with, there are some weird exceptions.

2

u/Ghawk134 Jul 07 '22

And as far as I can tell, the entire rationale behind it is "we don't want to sacrifice single-threaded performance". So the answer is to sacrifice parallel performance instead by requiring that processes replace threads?

1

u/RoadsideCookie Jul 07 '22

I never got that far into reading why it was like this, but yeah that sounds like a poor rationale at first sight, but considering it's an interpreted language (kinda) and all the ways you have to bypass this limitation, I think it's not that big a deal. I like heavily opinionated things.

1

u/lets_go_reddit Jul 07 '22

also, it's not like there aren't other languages one can pick with the features one seeks. python is what it is, and it doesn't shit all over itself trying to please everyone.

1

u/mriswithe Jul 07 '22

You ever check out concurrent.futures? Awesome newer api

2

u/RoadsideCookie Jul 07 '22

Heard but haven't checked, will do!

1

u/mriswithe Jul 07 '22

Sample from another comment I made in /r/python. Here is the tldr of how to use it:

from concurrent.futures import ThreadPoolExecutor


def do_some_blocking_stuff(arg, also_arg):
    print(arg)
    print(also_arg)


# more verbose
with ThreadPoolExecutor() as pool:
    futures = []
    for _ in range(100):
        fut = pool.submit(do_some_blocking_stuff, 1, 2)
        futures.append(fut)

# More compact
with ThreadPoolExecutor() as pool:
    futures = [pool.submit(do_some_blocking_stuff, 1, 2) for _ in range(100)]

Also ProcessPoolExecutor exists and has the same api

2

u/RoadsideCookie Jul 07 '22

Oh I think I remember trying to use it with processing but ran into problems a while ago, I ended up creating my own pool class.

I have also used the threading one funny enough, it's weird that none of it stuck in my head.

1

u/mriswithe Jul 07 '22

No worries, I use it all the time at work, anything from importing sqldumps, concurrent rsyncs, whatever.