加锁保护数据安全,但导致加锁部分串行执行,效率降低
--加锁后要考虑释放锁,不建议使用
from multiprocessing import Process,Lock import time def work(lock): mutex.acquire() print("target %s is running" %os.getpid()) time.sleep(2) print("target %s is done" %os.getpid()) mutex.release() if __name__=="__main__": mutex=Lock() for i in range(3): p=Process(target=work,args=(mutex,)) #mutex需要传参 p.start() print("主进程") ‘‘‘ target 10879 is running 主进程 target 10879 is done target 10880 is running target 10880 is done target 10883 is running target 10883 is done ‘‘‘
#线程加锁 from threading import Thread,Lock,current_thread import time def work(): mutex.acquire() print("target %s is running" %current_thread().getName()) time.sleep(2) print("target %s is done" %current_thread().getName()) mutex.release() if __name__=="__main__": mutex=Lock() for i in range(3): t=Thread(target=work) #mutex不需要传参 t.start() print("主线程") ‘‘‘ 主线程 target Thread-615 is running target Thread-615 is done target Thread-616 is running target Thread-616 is done target Thread-617 is running target Thread-617 is done ‘‘‘
原文:https://www.cnblogs.com/hapyygril/p/12589694.html