python 线程 event.wait() 在多个线程中使用相同的对象

问题描述 投票:0回答:2

python3 线程库的

event.wait()
方法的文档在哪里,该方法解释了如何在不同线程中多次使用 1
event

下面的示例显示相同的

event
可以在多个线程中使用,每个线程都有不同的
wait()
持续时间,可能是因为每个线程都有自己的锁。

但是这个功能并没有以明显的方式记录在线程页面上。

这很有效,但不清楚为什么它有效,或者这是否会在未来的 python 版本中继续有效。

有什么方法可以让这个意外发生吗?

继承的事件只要在单独的线程中使用,就可以在多个类中正常工作吗?

import logging
import threading
import time

logging.basicConfig(level=logging.DEBUG,
                    format='[%(levelname)s] (%(threadName)-10s) %(message)s',)

def worker(i,dt,e):
    tStart=time.time()
    e.wait(dt)
    logging.debug('{0} tried to wait {1} seconds but really waited {2}'.format(i,dt, time.time()-tStart ))


e = threading.Event()

maxThreads=10
for i in range(maxThreads):
    dt=1+i # (s)
    w = threading.Thread(target=worker, args=(i,dt,e))
    w.start()

输出:

[DEBUG] (Thread-1  ) 0 tried to wait 1 seconds but really waited 1.0003676414489746
[DEBUG] (Thread-2  ) 1 tried to wait 2 seconds but really waited 2.00034761428833
[DEBUG] (Thread-3  ) 2 tried to wait 3 seconds but really waited 3.0001776218414307
[DEBUG] (Thread-4  ) 3 tried to wait 4 seconds but really waited 4.000180244445801
[DEBUG] (Thread-5  ) 4 tried to wait 5 seconds but really waited 5.000337362289429
[DEBUG] (Thread-6  ) 5 tried to wait 6 seconds but really waited 6.000308990478516
[DEBUG] (Thread-7  ) 6 tried to wait 7 seconds but really waited 7.000143051147461
[DEBUG] (Thread-8  ) 7 tried to wait 8 seconds but really waited 8.000152826309204
[DEBUG] (Thread-9  ) 8 tried to wait 9 seconds but really waited 9.00012469291687
[DEBUG] (Thread-10 ) 9 tried to wait 10 seconds but really waited 10.000144481658936
python-3.x multithreading events
2个回答
0
投票

由于 e 正在线程化事件, 您在本地为每个线程声明它(所有 10 个线程几乎并行执行)。 您可以在这里查看:

import logging
import threading
import time

logging.basicConfig(level=logging.DEBUG,
                    format='[%(levelname)s] (%(threadName)s) %(message)s',)

def worker(i,dt,e):
    tStart=time.time()
    logging.info('Program will wait for {} time while trying to print the change from {} to {}'.format(dt,i,dt))
    e.wait(dt)
    logging.debug('{0} tried to wait {1} seconds but really waited {2}'.format(i,dt, time.time()-tStart ))


e = threading.Event()

maxThreads=10
for i in range(maxThreads):
    dt=1+i # (s)
    w = threading.Thread(target=worker, args=(i,dt,e))
    w.start()

这不是锁定,它只是关于传递到线程目标的值


0
投票

您描述的场景是预期用途,即使从文档中可能无法立即明显看出。

Event
threading.Condition
周围的薄包装纸。 (来源

Event.set
使用
Condition.notify_all
来实际触发事件。查看 notify_all
docstring
,它说:“唤醒在此条件下等待的所有线程。...”(Py 3.12)。

所以继续吧,不用担心:-)

© www.soinside.com 2019 - 2024. All rights reserved.