正如标题所说,对 threading.currentThread().ident
的不同调用返回 34382823872,即使在不同的进程中也是如此。 (使用 Python 3.1 和 FreeBSD)
是不是FreeBSD的python线程问题?
最佳答案
你在 REPL 中测试这个吗?还是在实际程序中?我问是因为当我使用 REPL 运行以下命令时,我得到了相同的结果,但是当我运行与脚本相同的命令时,线程具有不同的标识符。
import threading
def thid():
print threading.currentThread().ident
t1 = threading.Thread(target=thid)
t2 = threading.Thread(target=thid)
t1.start()
t2.start()
t1.join()
t2.join()
REPL 输出:
>>> t1.start()
4301111296
>>> t2.start()
4301111296
脚本输出:
me@mine:~ $ python th.py
4300935168
4302835712
我怀疑这是预期的行为;以下来自threading
文档:
The ‘thread identifier’ of this thread or None if the thread has not been started. This is a nonzero integer. See the thread.get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created.
此外,我在 REPL 中修改了 thid
如下:
>>> def thid():
... print threading.currentThread().ident
... sleep(10)
当我在调用 t1.start()
的 10 秒内调用 t2.start()
时,它们有不同的 ID,但如果我等待超过 10 秒,他们有相同的ID。
如果要区分不同的线程,调用id(threading.currentThread())
即可。 Python id 总是不同的。
关于Python & FreeBSD : threading. currentThread().ident 即使在不同的进程中也返回相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5688503/