gpt4 book ai didi

python - 我可以同时在 Python 中运行多个计时器吗?

转载 作者:太空宇宙 更新时间:2023-11-04 01:15:19 25 4
gpt4 key购买 nike

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

在为某些请求找到路由后,应激活计时器以在特定保持时间间隔到期后更新剩余链路容量的值。我知道我可以使用 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。你知道如何解决这个问题吗?

最佳答案

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

您可以使用 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

关于python - 我可以同时在 Python 中运行多个计时器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25021842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com