Skip to content

Instantly share code, notes, and snippets.

@ariesduanmu
Created November 20, 2020 08:07
Show Gist options
  • Select an option

  • Save ariesduanmu/9b4df46c3a0c45c71116feb13cc164f7 to your computer and use it in GitHub Desktop.

Select an option

Save ariesduanmu/9b4df46c3a0c45c71116feb13cc164f7 to your computer and use it in GitHub Desktop.
multiprocess_demo
# -*- coding: utf-8 -*-
from multiprocessing import Process, Lock
from time import sleep
import sys
from time import time
def worker(lock, i, start, sleep_second):
lock.acquire()
try:
sleep(sleep_second)
except Exception as e:
print(f"Error:{e}")
finally:
lock.release()
if __name__ == "__main__":
lock = Lock()
failed = []
for i in range(4):
start = time()
sleep_second = [4, 1, 0, 4][i]
print(f"[*] Start({i}):{time()-start}/{sleep_second}")
process = Process(target=worker, args=(lock, i, start, sleep_second))
process.start()
sleep(3)
if not lock.acquire(False):
print(f"[-] Fail({i}):{time()-start}")
failed += [i]
else:
print(f"[+] Success({i}):{time()-start}")
lock.release()
print(f"[*] Kill Process({i})\n")
process.terminate()
process.join()
print(f"[*] Failed:{failed}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment