我使用pytest创建了一个小测试用例来演示该问题:
from threading import Thread, get_ident
def test_threading():
threads = []
ids = []
def append_id():
# time.sleep(1)
ids.append(get_ident())
for _ in range(5):
thread = Thread(target=append_id)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
assert len(set(ids)) == 5
测试失败,因为get_ident
为不同的线程返回相同的ID.但当我在每个线程中添加time.sleep(1)
时,测试通过了.
我正在使用Python 3.9.0和Pytest 7.1.2.