Last active
August 19, 2021 16:11
-
-
Save zyxue/77232cb720c641bcd9cf7f81ae06f1b1 to your computer and use it in GitHub Desktop.
python multiprocessing lock example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import multiprocessing | |
import multiprocessing.synchronize | |
import random | |
import time | |
def print_func(process_index: int) -> None: | |
for x in "hello world": | |
print(x, end='', flush=True) | |
# sleep a random amount of seconds to scramble the order of printed characters. | |
time.sleep(random.random() / 10) | |
print(' ', process_index, flush=True) | |
def demo_func_no_lock(process_index: int) -> None: | |
print_func(process_index) | |
def demo_func_with_lock(lock: multiprocessing.synchronize.Lock, process_index: int) -> None: | |
lock.acquire() | |
print_func(process_index) | |
lock.release() | |
if __name__ == "__main__": | |
lock = multiprocessing.Lock() | |
procs = [] | |
for index in range(4): | |
# TODO: uncomment one of the two lines below to see the difference in print output. | |
# proc = multiprocessing.Process(target=demo_func_no_lock, args=(index,)) | |
# proc = multiprocessing.Process(target=demo_func_with_lock, args=(lock, index)) | |
procs.append(proc) | |
proc.start() | |
for proc in procs: | |
proc.join() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment