by BiteCode_dev · 6y ago · 0 comments
However, if you try to just get work done in Python, this is not what you want.
Don't do threads/processes yourself, use pools:
import random
import time
from concurrent.futures import ProcessPoolExecutor, as_completed
def hello():
seconds = random.randint(0, 5)
print(f"Start blocking for {seconds}s")
time.sleep(seconds)
print(f"Stopped blocking after {seconds}s")
return seconds
if __name__ == "__main__":
with ProcessPoolExecutor(max_workers=2) as exec:
a = exec.submit(hello)
b = exec.submit(hello)
for future in as_completed((a, b)):
print(future.result())
And don't manage the loop yourself. Use Python 3.7, and replace: loop = asyncio.get_event_loop()
loop.run_until_complete(loop.create_task(foo()))
loop.close()
With:
asyncio.run(foo())The code is not just shorter, it is way, wayyyyyyyyyyyy, more correct.
Also don't program asyncio by hand. Use a lib. E.G: wanna do http, use aiohttp.
This is Python, don't suffer more than you need to.
However, I don't think use threads/processes is a bad idea. A pool gives you a constrain to utilize threads/processes, but sometime we may want to adjust the number of threads/processes based on system load. Under this circumstance, using a pool is not the best choice.
Also what exactly would that newbie be building that starts and stops threads depending on the system load? What kind of a contraption is that? What are you doing?
Finallizing all of the above: under the circumstance you mentioned, you should check whether you have just seriously over-architected the solution.
Also, I did not advocate a newbie should start and stop threads by themselves. I want to say I agree that we should use high-level APIs in most cases, but, in some cases, we may need to use low-level APIs to achieve our missions. I am unwilling to limit what kind of APIs should use. In my opinion, like you said: "you have just seriously over-architected the solution," we should be careful to use APIs. Even though high-level APIs are safer, programmers may misuse them.
Just an effortless programming experience.