Threading Barrier 代码笔记

发布时间:2020-05-17 06:13:21 作者:windcharger
来源:网络 阅读:516

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()
推荐阅读:
  1. threading.local 代码笔记
  2. threading.Timer 延迟执行实例代码

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

barrier threading python

上一篇:网络运维——访问共享的三种方式

下一篇:ldifde -j c:\ -f users.ldf 此命令可以导出全部域的项目

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》