溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Threading Barrier 代碼筆記

發(fā)布時(shí)間:2020-05-17 06:13:21 來(lái)源:網(wǎng)絡(luò) 閱讀:517 作者:windcharger 欄目:編程語(yǔ)言

Barrier簡(jiǎn)單演示

import threading
import logging

FORMAT = '%(threadName)s %(thread)d %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)

def worker(barrier:threading.Barrier):
    logging.info("waiting for {} threading. ".format(barrier.n_waiting))
    try:
        barrier_id = barrier.wait()
        logging.info('after barrier {}'.format(barrier_id))  # 顯示等待的barrier實(shí)例數(shù)量
    except threading.BrokenBarrierError:
        logging.info('Broken Barrier')

barrier = threading.Barrier(3)

for x in range(5):
    threading.Event().wait(2)
    threading.Thread(target=worker, name='worker-{}'.format(x), args=(barrier, )).start()

Barrier之 broken的代碼演示

import threading
import logging

FORMAT = '%(threadName)s %(thread)d %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)

def worker(barrier:threading.Barrier):
    logging.info('waitting for {} threads'.format(barrier.n_waiting))
    try:
        barrier_id = barrier.wait()
        logging.info('after barrier {}'.format(barrier_id))
    except threading.BrokenBarrierError:
        logging.info('broken barrier')

barrier = threading.Barrier(3)

for i in range(0, 9):
    if i == 2:
        barrier.abort()
    elif i == 6:
        barrier.reset()
        threading.Event().wait(2)
    threading.Thread(target=worker, args=(barrier, )).start()

Barrier之 wait方法超時(shí)演示

import threading
import logging

FORMAT = '%(threadName)s %(thread)d %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)

def worker(barrier:threading.Barrier, i:int):
    logging.info('waitting for {} threads'.format(barrier.n_waiting))
    try:
        if i < 3:
            barrier_id = barrier.wait(1)  # 設(shè)定超時(shí)時(shí)間
        else:
            if i == 6:
                barrier.reset()  # 恢復(fù)屏障
            barrier_id = barrier.wait()
        logging.info('after barrier {}'.format(barrier_id))
    except threading.BrokenBarrierError:
        logging.info('broken barrier')

barrier = threading.Barrier(3)

for i in range(0, 9):
    threading.Event().wait(2)
    threading.Thread(target=worker, args=(barrier, i)).start()
向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI