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

2024-04-28 22:53:31 发布

您现在位置:Python中文网/ 问答频道 /正文

为了测试一些路由算法,我试图对电信网络进行仿真。请求是根据泊松分布来的,它们的保持时间服从指数分布。在

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

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

    def hello(i):
       print i

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

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

^{pr2}$

所以,看来我不能用定时器来达到这个目的。你知道怎么解决这个问题吗?在


Tags: 函数网络算法路由hello间隔时间链路
1条回答
网友
1楼 · 发布于 2024-04-28 22:53:31

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

可以使用锁对象阻止线程同时访问某些资源。在您的示例中,您需要限制对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()

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

^{pr2}$

相关问题 更多 >