【问题标题】:Can I run multiple Timers in Python simultaneously?我可以同时在 Python 中运行多个计时器吗?
【发布时间】:2014-07-29 17:51:43
【问题描述】:

我正在尝试模拟电信网络以测试一些路由算法。请求按照泊松分布,其持有时间服从指数分布。

在为某些请求找到路由后,应激活计时器以在特定保持时间间隔到期后更新剩余链路容量的值。我知道我可以使用 threading.Timer 延迟调用某些函数,但在等待时间到期之前,许多其他请求将到达,我需要为每个请求运行单独的 Timer。

与我的算法无关,今天我尝试运行这段代码:

    def hello(i):
       print i

    for i in range(0,10):
      t = threading.Timer(2,hello,[i])
      t.start()

我想以 2 秒的间隔打印范围 (0,10) 中的数字,但输出完全奇怪。几秒钟后,我得到了:

0
1
32

4
5
6
7
89

所以,我似乎不能为此目的使用 Timer。你知道如何解决这个问题吗?

【问题讨论】:

  • 您在 10 个不同的线程中打印,因此它们的输出将交错(例如,32 在同一行上)。如果您想在一个线程中运行所有这些并在每次调用之间等待 2 秒,只需在您的 for 循环中使用 time.sleep(2) 并调用 hello()

标签: python python-2.7 networking timer


【解决方案1】:

如果两个线程同时打印,则一个线程可能会在另一个线程完成之前开始打印。这可能会导致两条消息出现在一行上,或者一行中的两条换行符被打印出来而没有内容。

您可以使用 Lock 对象防止线程同时访问某些资源。在您的示例中,您可能希望限制对 print 的访问。

import threading

print_lock = threading.Lock()

def hello(i):
    #no other thread can execute `hello` as long as I hold this lock.
    print_lock.acquire()

    print i

    #I'm done printing. Other threads may take their turn now.
    print_lock.release()

for i in range(0,10):
    t = threading.Timer(2,hello,[i])
    t.start()

结果(多种可能性中的一种):

1
2
0
4
3
6
5
8
7
9

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多