我正在尝试模拟电信网络以测试某些路由算法。请求遵循泊松分布,其保留时间遵循指数分布。
在找到某些请求的路由后,应激活计时器,以在特定的保持时间间隔到期后更新剩余链路容量的值。我知道我可以使用 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
所以,看来我不能使用 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/