【问题标题】:python threading event.wait() using same object in multiple threadspython threading event.wait() 在多个线程中使用相同的对象
【发布时间】:2022-01-02 16:21:47
【问题描述】:

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

下面的示例显示了相同的event 可以在多个线程中使用,每个线程具有不同的wait() 持续时间,可能是因为每个线程都有自己的内部锁。

但此功能并未以明显的方式记录在 threading page 上。

这很好用,但不清楚为什么它会起作用,或者这是否会在未来的 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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-18
      • 1970-01-01
      • 1970-01-01
      • 2018-08-22
      • 1970-01-01
      相关资源
      最近更新 更多