gpt4 book ai didi

Python/线程/屏障 : Is this a correct usage of Barrier?

转载 作者:太空宇宙 更新时间:2023-11-03 14:44:48 25 4
gpt4 key购买 nike

可能是我没有理解线程的屏障概念。但是我写了一段代码,我想了解它是否正确使用了 barrier。

代码如下:

#!/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()

最佳答案

屏障设置了线程的计数,这些线程将一起等待直到达到该计数。测试中有一个小的变化

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()

您可以看到所有线程在不同的时间从 sleep 中唤醒,但同时从 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

关于Python/线程/屏障 : Is this a correct usage of Barrier?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50437749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com