Skip to content

Instantly share code, notes, and snippets.

@jvkersch
Created February 14, 2020 09:22
Show Gist options
  • Select an option

  • Save jvkersch/2275bdff86ba6886e61ba768e4883ec1 to your computer and use it in GitHub Desktop.

Select an option

Save jvkersch/2275bdff86ba6886e61ba768e4883ec1 to your computer and use it in GitHub Desktop.
""" Mixing threads and processes (fork) is a bad idea.
When a process forks, only the thread that was running at the time of the
fork is copied to the child process. That means that if a lock was acquired
by a background thread in the main process, that lock will appear as locked
in the child process, with no way to unlock it.
"""
import os
import multiprocessing
import threading
lock = threading.Lock()
event = threading.Event()
def lock_then_unlock():
print("acquiring lock in process", os.getpid())
lock.acquire()
event.wait()
print("releasing lock in process", os.getpid())
lock.release()
def main():
acquire = threading.Thread(target=lock_then_unlock)
acquire.start()
pid = os.fork()
if pid == 0: # child
print("child")
print(lock.locked())
print("acquiring lock again in child")
lock.acquire()
else:
# parent
print("parent")
event.set()
acquire.join()
os.wait()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment