Created
February 14, 2020 09:22
-
-
Save jvkersch/2275bdff86ba6886e61ba768e4883ec1 to your computer and use it in GitHub Desktop.
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
| """ 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