Friday 17 January 2020

python threading

threading is better for IO-bound tasks. an IO-bound job is dominated by a lot of waiting on input/output to complete. multiprocessing is ideal for CPU-bound tasks.

#pycharm
import time
import threading

start = time.perf_counter()

def do_something(num):
    print(f'thread {num} starts...')
    time.sleep(1)
    with open('a.txt', 'a') as file:
        file.writelines(f'running thread {num}\n')
    print(f'Done thread {num}')

processes = []

if __name__ ==  '__main__':

    for i in range(10):
        p = threading.Thread(target=do_something, args=[i])
        p.start()
        processes.append(p)

    for process in processes:
        process.join()

    finish = time.perf_counter()

    print(f'finish in {round(finish-start, 3)} seconds')

-------------------------
#logs

thread 0 starts...
thread 1 starts...
thread 2 starts...
thread 3 starts...
thread 4 starts...
thread 5 starts...
thread 6 starts...
thread 7 starts...
thread 8 starts...
thread 9 starts...
Done thread 0
Done thread 1
Done thread 2
Done thread 4
Done thread 3
Done thread 9
Done thread 6
Done thread 8
Done thread 5
Done thread 7
finish in 1.019 seconds

#a.txt

running thread 0
running thread 2
running thread 1
running thread 4
running thread 3
running thread 7
running thread 6
running thread 5
running thread 9
running thread 8

reference:
https://www.youtube.com/watch?v=IEEhzQoKtQU
https://realpython.com/async-io-python/

No comments:

Post a Comment