python - 在 python 2.6 中获取线程 ID 或名称

标签 python multithreading

我试图在 python 2.6 中获取线程 ID 或名称 我按照示例进行操作,但出现错误 喜欢 未定义全局名称“currentThread” 未定义全局名称“current_thread”

(我尝试了 currentThread 和 current_thread)

这是我的代码:

vim f3Q.py
  1 import Queue
  2 from threading import Thread
  3
  4 def do_work(item):
  5         try:
  6                 print current_thread().getName()
  7
  8
  9         except Exception as details:
 10                 print details
 11                 pass
 12         print item*2
 13
 14 def worker():
 15         while True:
 16                 item=q.get()
 17                 do_work(item)
 18                 q.task_done()
 19
 20 q=Queue.Queue()
 21 l=[13,26,77,99,101,4003]
 22 for item in l:
 23         q.put(item)
 24
 25
 26 for i in range (4):
 27         t=Thread(target=worker,name="child"+str(i))
 28         t.daemon=True
 29         t.start()
 30
 31
 32 q.join()
 33

更新: 我根据 Mata 给出的提示修复了错误 我也应该导入 current_thread()。

from threading import Thread,current_thread

最佳答案

你没有导入threading,只有Thread

要么导入threading,要么直接导入current_thread:

1 import Queue
2 from threading import Thread, current_thread
3
4 def do_work(item):
5         try:
6                 print current_thread()

关于python - 在 python 2.6 中获取线程 ID 或名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17707775/

相关文章:

Python 变量和文件名冲突

java - Android ThreadPoolExecutor 和 join()

python - 字典中的错误求和值

带有 Image.ANTIALIAS 的 Python PIL 缩略图。如何保持质量

multithreading - 使用 GO 时如何测量系统过载

ios - iOS6 中无法从后台线程调用主线程上的代码

两个线程可以写入同一数组的不同元素吗?

c++ - 通过线程实现游戏引擎确定性

Python:尝试将字符串转换为 int,对于以 10 为基数的 int(),出现 int 无效文字错误: ''

python - 桌面外的 Tkinter 窗口