ThreadingBarrier代码笔记

Barrier简单演示

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实例数量
    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方法超时演示

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)  # 设定超时时间
        else:
            if i == 6:
                barrier.reset()  # 恢复屏障
            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()

本文标题:ThreadingBarrier代码笔记
分享链接:http://bzwzjz.com/article/jjohsd.html

其他资讯

Copyright © 2007-2020 广东宝晨空调科技有限公司 All Rights Reserved 粤ICP备2022107769号
友情链接: 网站制作公司 成都h5网站建设 网站制作 高端网站设计 企业网站设计 手机网站制作 网站建设 自适应网站建设 企业网站建设 企业网站建设公司 品牌网站建设 网站设计 成都响应式网站建设 成都网站建设 温江网站设计 成都网站设计 成都网站建设公司 成都网站建设 重庆电商网站建设 网站制作 成都企业网站建设 攀枝花网站设计