我可以同时在Python中运行多个定时器吗?

2 投票
1 回答
9038 浏览
提问于 2025-04-18 15:13

我正在尝试模拟一个电信网络,以测试一些路由算法。请求的到达是根据泊松分布的,而它们的保持时间则遵循指数分布。

在为某个请求找到路由后,应该启动一个定时器,以便在特定的保持时间结束后更新剩余链路的容量值。我知道可以使用 threading.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

所以,看起来我不能用定时器来实现这个目的。你有没有什么想法可以解决这个问题?

1 个回答

3

如果两个线程同时打印信息,可能会出现一个线程在另一个线程完成之前就开始打印的情况。这可能导致两条信息挤在一行上,或者连续打印出两个空行。

你可以使用一个叫做锁(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

撰写回答