1. 程式人生 > >python 歸納 (二四)_多進程數據共享和同步_鎖Lock&RLock

python 歸納 (二四)_多進程數據共享和同步_鎖Lock&RLock

time base 多進程 pro process 歸納 print 數據共享 創建

# -*- coding: utf-8 -*-
"""
多進程 鎖使用

邏輯:
    10個進程各種睡眠2秒,然後打印。
    不加鎖同時打印出來,總共2秒,加鎖一個接一個打印,總共20秒

總結:
    1、Lock 只要1把鎖,RLock 有多把鎖,但是不清楚什麽場景只適合用RLock

使用:
    1. 創建所   lock = Lock() or lock = RLock()
    2. 把鎖當做參數傳入給子進程
    3. 在子進程執行代碼中對代碼塊,加鎖 lock.acquire(); 其他代碼 lock.release()

"""
from multiprocessing import Process, Lock, RLock import time # 不加鎖 def f(l, i): time.sleep(2) print(time.strftime(%M:%S, time.localtime(time.time())),hello world, i) # 加Lock def f2(l, i): l.acquire() # 競爭鎖 time.sleep(2) print(time.strftime(%M:%S, time.localtime(time.time())),
hello world, i) l.release() # 釋放鎖 # 加Rlock def f3(l, i): l.acquire() # 競爭鎖 l.acquire() # 搶到鎖後,再加一把鎖 time.sleep(2) print(time.strftime(%M:%S, time.localtime(time.time())),hello world, i) l.release() # 釋放鎖 l.release() # 前面幾個acquire,這裏就有幾個 release 如果註釋掉,其他進程阻塞
if __name__ == __main__: lock = Lock() rlock = RLock() import ptools;ptools.checkname(rlock);exit(0) # base # for num in range(10): # Process(target=f, args=(None, num)).start() # case1 for num in range(10): Process(target=f2, args=(lock, num)).start() # # # case2 # for num in range(10): # Process(target=f3, args=(rlock, num)).start() """ Out: 不加鎖 (‘49:31‘, ‘hello world‘, 3) (‘49:31‘, ‘hello world‘, 2) (‘49:31‘, ‘hello world‘, 1) (‘49:31‘, ‘hello world‘, 7) (‘49:31‘, ‘hello world‘, 8) (‘49:31‘, ‘hello world‘, 5) (‘49:31‘, ‘hello world‘, 6) (‘49:31‘, ‘hello world‘, 4) (‘49:31‘, ‘hello world‘, 9) (‘49:31‘, ‘hello world‘, 0) case1 加鎖,case2差不多 ‘49:52‘, ‘hello world‘, 0) (‘49:54‘, ‘hello world‘, 7) (‘49:56‘, ‘hello world‘, 2) (‘49:58‘, ‘hello world‘, 5) (‘50:00‘, ‘hello world‘, 4) (‘50:02‘, ‘hello world‘, 3) (‘50:04‘, ‘hello world‘, 8) (‘50:06‘, ‘hello world‘, 1) (‘50:08‘, ‘hello world‘, 6) (‘50:10‘, ‘hello world‘, 9) """

python 歸納 (二四)_多進程數據共享和同步_鎖Lock&RLock