螺纹.get_ident()在运行pytest时在不同线程之间返回相同的ID
我已经使用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。
I have created a small test case using pytest to demonstrate the issue:
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
The test is failing because get_ident
returns the same ID for different threads. But when I add time.sleep(1)
in each thread, the test passes.
I'm not sure I understand why.
I'm using Python 3.9.0 and Pytest 7.1.2.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自 documentation :
由于您的线程运行太快(没有
time.sleep(1)
),因此ID被回收。您可以向每个线程提供
名称
。此 name 您可以在测试中使用它(或在应用程序中,如果您需要在上下文中唯一的东西):From the documentation of
get_ident
:Since your threads are running too quickly (without the
time.sleep(1)
), the ids are being recycled.You can provide a
name
to each thread. This name does not have to be unique, but you can use it in your test (or in your application, if you need something that is unique in a context):