Python / Threading / Barrier:这是Barrier的正确用法吗?

时间:2018-05-20 17:48:39

标签: python multithreading

也许我还没有理解线程的障碍概念。但我写了一个代码,我想知道它是否正确使用屏障。

以下是代码:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time
import random
import threading


def f(b):
    time.sleep(random.randint(2, 10))
    print("{} passed the barrier at: {}".format(threading.current_thread().getName(), time.ctime()))
    b.wait()


barrier = threading.Barrier(3)
for i in range(3):
    t = threading.Thread(target=f, args=(barrier,))
    t.start()

1 个答案:

答案 0 :(得分:3)

屏障设置一个线程计数,它们将一起等待,直到达到该计数。随着测试的微小变化

import time
import random
import threading

def f(b):
    time.sleep(random.randint(2, 10))
    print("{} woke at: {}".format(threading.current_thread().getName(), time.ctime()))
    b.wait()
    print("{} passed the barrier at: {}".format(threading.current_thread().getName(), time.ctime()))

barrier = threading.Barrier(3)
for i in range(3):
    t = threading.Thread(target=f, args=(barrier,))
    t.start()

您可以看到所有线程在不同时间从睡眠状态唤醒,但同时从wait返回。

$ python3 o.py
Thread-2 woke at: Sun May 20 11:59:16 2018
Thread-3 woke at: Sun May 20 11:59:21 2018
Thread-1 woke at: Sun May 20 11:59:22 2018
Thread-1 passed the barrier at: Sun May 20 11:59:22 2018
Thread-2 passed the barrier at: Sun May 20 11:59:22 2018
Thread-3 passed the barrier at: Sun May 20 11:59:22 2018