Python多進(jìn)程同步Lock、Semaphore、Event實(shí)例
同步的方法基本與多線程相同。
1) Lock
當(dāng)多個(gè)進(jìn)程需要訪問共享資源的時(shí)候,Lock可以用來避免訪問的沖突。
import multiprocessing
import sys
def worker_with(lock, f):
with lock:
fs = open(f,"a+")
fs.write('Lock acquired via with\n')
fs.close()
def worker_no_with(lock, f):
lock.acquire()
try:
fs = open(f,"a+")
fs.write('Lock acquired directly\n')
fs.close()
finally:
lock.release()
if __name__ == "__main__":
f = "file.txt"
lock = multiprocessing.Lock()
w = multiprocessing.Process(target=worker_with, args=(lock, f))
nw = multiprocessing.Process(target=worker_no_with, args=(lock, f))
w.start()
nw.start()
w.join()
nw.join()
在上面的例子中,如果兩個(gè)進(jìn)程沒有使用lock來同步,則他們對(duì)同一個(gè)文件的寫操作可能會(huì)出現(xiàn)混亂。
2)Semaphore
Semaphore用來控制對(duì)共享資源的訪問數(shù)量,例如池的最大連接數(shù)。
import multiprocessing
import time
def worker(s,i):
s.acquire()
print(multiprocessing.current_process().name + " acquire")
time.sleep(i)
print(multiprocessing.current_process().name + " release")
s.release()
if __name__ == "__main__":
s = multiprocessing.Semaphore(2)
for i in range(5):
p = multiprocessing.Process(target=worker, args=(s,i*2))
p.start()
上面的實(shí)例中使用semaphore限制了最多有2個(gè)進(jìn)程同時(shí)執(zhí)行。
3)Event
Event用來實(shí)現(xiàn)進(jìn)程間同步通信。
import multiprocessing
import time
def wait_for_event(e):
"""Wait for the event to be set before doing anything"""
print ('wait_for_event: starting')
e.wait()
print ('wait_for_event: e.is_set()->' + str(e.is_set()))
def wait_for_event_timeout(e, t):
"""Wait t seconds and then timeout"""
print ('wait_for_event_timeout: starting')
e.wait(t)
print ('wait_for_event_timeout: e.is_set()->' + str(e.is_set()))
if __name__ == '__main__':
e = multiprocessing.Event()
w1 = multiprocessing.Process(name='block',
target=wait_for_event,
args=(e,))
w1.start()
w2 = multiprocessing.Process(name='non-block',
target=wait_for_event_timeout,
args=(e, 2))
w2.start()
time.sleep(3)
e.set()
print ('main: event is set')
#the output is:
#wait_for_event_timeout: starting
#wait_for_event: starting
#wait_for_event_timeout: e.is_set()->False
#main: event is set
#wait_for_event: e.is_set()->True
相關(guān)文章
解決pytorch load huge dataset(大數(shù)據(jù)加載)
這篇文章主要介紹了解決pytorch load huge dataset(大數(shù)據(jù)加載)的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05python實(shí)戰(zhàn)教程之自動(dòng)掃雷
用python實(shí)現(xiàn)掃雷,非常有意思,這篇文章主要給大家介紹了關(guān)于python實(shí)現(xiàn)自動(dòng)掃雷的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-07-07python解析發(fā)往本機(jī)的數(shù)據(jù)包示例 (解析數(shù)據(jù)包)
這篇文章主要介紹了使用python解析獲取發(fā)往本機(jī)的數(shù)據(jù)包,并打印出來, 大家參考使用吧2014-01-01基于Django集成CAS實(shí)現(xiàn)流程詳解
這篇文章主要介紹了基于Django集成CAS實(shí)現(xiàn)流程詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11Python機(jī)器學(xué)習(xí)多層感知機(jī)原理解析
最簡單的深度網(wǎng)絡(luò)稱為多層感知機(jī),它們由多層神經(jīng)元組成,每一層都與下面一層(從中接收輸入)和上面一層(反過來影響當(dāng)前層的神經(jīng)元)完全相連2021-10-10