Skip to content

Instantly share code, notes, and snippets.

@zyxue
Last active August 19, 2021 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zyxue/77232cb720c641bcd9cf7f81ae06f1b1 to your computer and use it in GitHub Desktop.
Save zyxue/77232cb720c641bcd9cf7f81ae06f1b1 to your computer and use it in GitHub Desktop.
python multiprocessing lock example
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