简体   繁体   English

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

[英]Can I run multiple Timers in Python simultaneously?

I am trying to make simulation of telecommunication network in order to test some routing algorithm. 我正在尝试对电信网络进行仿真,以测试某些路由算法。 Requests come according to Poisson distribution and their holding times follow exponential distribution. 请求根据Poisson分布而来,并且其保持时间遵循指数分布。

After finding route for some request Timer should be activated to update values of residual link capacities after expiration of specific holding time interval. 找到某个请求的路由后,应在特定的保持时间间隔到期后激活计时器以更新剩余链路容量的值。 I know that I can use threading.Timer to call some function with delay, but before holding time expires many other request will arrive and I need to run separate Timer for each of them. 我知道我可以使用threading.Timer延迟调用某些函数,但是在保持时间到期之前,将有许多其他请求到达,并且我需要为每个请求运行单独的Timer。

Not related with my algorithm, today I tried to run this code: 与我的算法无关,今天我尝试运行以下代码:

    def hello(i):
       print i

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

I wanted to print numbers from range (0,10) in intervals of 2 seconds, but output is totally weird. 我想以2秒的间隔打印范围(0,10)内的数字,但是输出却很奇怪。 After few seconds I got: 几秒钟后,我得到:

0
1
32

4
5
6
7
89

So, it seems that I cannot use Timer for this purpose. 因此,看来我不能为此使用Timer。 Do you have some idea how to solve this problem? 您知道如何解决此问题吗?

If two threads print at the same time, it's possible for one thread to start printing before another one finishes. 如果同时打印两个线程,则一个线程有可能在另一线程完成之前就开始打印。 This may cause two messages to appear on one line, or for two newlines in a row to be printed with no content. 这可能会导致两条消息显示在一行上,或者导致一行中的两个换行在没有内容的情况下打印。

You can prevent threads from accessing some resource at the same time using a Lock object. 您可以使用Lock对象阻止线程同时访问某些资源。 In your example, you would want to restrict access to print . 在您的示例中,您想限制对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()

Result (one possibility of many): 结果(多种可能性之一):

1
2
0
4
3
6
5
8
7
9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM