簡體   English   中英

我可以同時在Python中運行多個計時器嗎?

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

我正在嘗試對電信網絡進行仿真,以測試某些路由算法。 請求根據Poisson分布而來,並且其保持時間遵循指數分布。

找到某個請求的路由后,應在特定的保持時間間隔到期后激活計時器以更新剩余鏈路容量的值。 我知道我可以使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM