Python 两个线程并行运行的奇怪输出

Python 两个线程并行运行的奇怪输出,python,python-multithreading,schedule,Python,Python Multithreading,Schedule,我的密码。它启动2个线程,内部调度程序每秒打印一次数字 import threading import time from datetime import datetime import schedule _lock = threading.Lock() def p(number): _lock.acquire() print(number, datetime.now()) _lock.release() def f(number): schedule

我的密码。它启动2个线程,内部调度程序每秒打印一次数字

import threading
import time
from datetime import datetime

import schedule

_lock = threading.Lock()


def p(number):
    _lock.acquire()
    print(number, datetime.now())
    _lock.release()


def f(number):
    schedule.every(5).seconds.do(p, number)
    while True:
        schedule.run_pending()
        time.sleep(1)


thread = threading.Thread(target=f, args=(1,))
thread2 = threading.Thread(target=f, args=(2,))
thread.start()
thread2.start()
预期产量

1 2020-03-25 22:07:17.817528
2 2020-03-25 22:07:17.817528
1 2020-03-25 22:07:22.821887
2 2020-03-25 22:07:22.821887
1 2020-03-25 22:07:27.826093
2 2020-03-25 22:07:27.826093
实际输出(见4,而不是17'处的2个打印,以及3,而不是27'处的2个打印)

我不知道为什么有时候线程触发器会不止一次地工作。
知道我做错了什么吗?

你正在经历一场所谓的灾难。两个线程正试图同时写入标准输出(即,
打印
),但它们能够获取此资源的顺序取决于计划程序的计时

为了解决这个问题,您需要引入一种方法来同步它们的访问,因此当一个线程试图打印某个内容时,另一个线程必须等待它完成

按如下方式修改代码:

导入线程
# ...
_lock=threading.lock()
def p(编号):
_lock.acquire()
打印(数字,结束=“”)
_lock.release()
# ...

1 2020-03-25 22:07:17.817528
2 2020-03-25 22:07:17.817528
1 2020-03-25 22:07:17.817528
2 2020-03-25 22:07:17.817528
1 2020-03-25 22:07:22.821887
2 2020-03-25 22:07:22.821887
1 2020-03-25 22:07:27.826093
2 2020-03-25 22:07:27.826093
2 2020-03-25 22:07:27.826093