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

时间:2013-07-17 18:45:06

标签: 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

2 个答案:

答案 0 :(得分:16)

您尚未导入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()

答案 1 :(得分:3)

这将有效

from threading import Thread, current_thread

    def do_work(item):
       print current_thread().name