在多个线程中使用同一对象的python线程处理事件.wait()



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

由于e是线程化Event,您为每个线程在本地声明它(所有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()

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

最新更新