Re:Java Is Underhyped
by AzzieElbab on Friday April 16, 2021 @06:54AM
(#26832266)
Even IO heavy code, it is much easier to write multithreaded async code for the jvm than it is for python
[ Parent
| on HN ]
Re:Java Is Underhyped
by BiteCode_dev on Friday April 16, 2021 @05:04PM
(#26839069)
If it's just about I/O, then no, threads in Python are super easy:
import random
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
def hello(seconds):
print(f"Starting hello in {seconds}s")
time.sleep(seconds)
print(f"End of hello in {seconds}s")
return seconds
# At the end of this blocks, it automatically join() and clean
with ThreadPoolExecutor(max_workers=2) as executor: # 2 tasks in parallel max
# this send jobs to threads via safe queues
a = executor.submit(hello, random.randint(0, 5))
b = executor.submit(hello, random.randint(0, 5))
# this collect results from queues in order of completion
# sync is automatic
for future in as_completed((a, b)):
print(future.result())
And if about network I/O only, you can get even more perfs using asyncio.Threads in Python are only inferior to Java threads when it's about using several CPU.
Are python threads still limited to one core? That’s always been a nasty limitation.
I do enjoy in python that it is quite easy to utilise multiple processes in a code-light fashion, but some things are more natural as threads.