首页 > 编程语言 > 详细

进程线程_Lock

时间:2020-03-28 22:04:30      阅读:61      评论:0      收藏:0      [点我收藏+]

加锁保护数据安全,但导致加锁部分串行执行,效率降低

--加锁后要考虑释放锁,不建议使用

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

 

进程线程_Lock

原文:https://www.cnblogs.com/hapyygril/p/12589694.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!