国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python多進程同步Lock、Semaphore、Event實例

2020-02-23 06:12:52
字體:
來源:轉載
供稿:網友

同步的方法基本與多線程相同。

1) Lock

當多個進程需要訪問共享資源的時候,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()

在上面的例子中,如果兩個進程沒有使用lock來同步,則他們對同一個文件的寫操作可能會出現混亂。

2)Semaphore

Semaphore用來控制對共享資源的訪問數量,例如池的最大連接數。

代碼如下:
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()

上面的實例中使用semaphore限制了最多有2個進程同時執行。

3)Event

Event用來實現進程間同步通信。

代碼如下:
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')

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 卢湾区| 武宣县| 松阳县| 上高县| 常德市| 滨海县| 武汉市| 车致| 无棣县| 察隅县| 田阳县| 梅州市| 神木县| 西贡区| 竹溪县| 昔阳县| 前郭尔| 类乌齐县| 焦作市| 建平县| 延边| 诏安县| 南乐县| 大荔县| 江阴市| 香港| 赫章县| 化德县| 秀山| 安康市| 广河县| 杨浦区| 台北县| 夏津县| 宁武县| 凯里市| 石景山区| 鞍山市| 许昌市| 通许县| 诸城市|