Process thread _Lock

Lock to protect data security, but lead to lock part serial execution, reducing efficiency

- After the lock releases the lock to be considered, not recommended

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
'''

 

Guess you like

Origin www.cnblogs.com/hapyygril/p/12589694.html