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

标签 python python-2.7 networking timer

我正在尝试模拟电信网络以测试某些路由算法。请求遵循泊松分布,其保留时间遵循指数分布。

在找到某些请求的路由后,应激活计时器,以在特定的保持时间间隔到期后更新剩余链路容量的值。我知道我可以使用 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/

相关文章:

windows - 路由来自特定应用程序的流量

linux - 将 IP 数据包从一个 IP 地址路由到另一个 IP 地址

C raw sockets 数据包看起来不错但没有逃脱网络

python - 尝试使用 Pandas 和 SQLAlchemy 从数据库导入时出错

python - 使用 SQLalchemy 将数据从一个数据库移动到另一个备份数据库的最简单方法是什么?

python - django.db.utils.OperationalError : (1426,“精度太大1000

python - joblib并行: reuse workers with the "with" statement

Python 天增量 : Remove time from days output in dataframe and convert column to float

python - 新手,对原始的网络表单感到困惑

python - 有没有更有效的方法来解决这个问题?