在python 2.6中获取线程ID或名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17707775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get thread ID or name in python 2.6
提问by Medya Gh
I am trying to get thread ID or name in python 2.6 I follow examples but I get errors like global name 'currentThread' is not defined global name 'current_thread' is not defined
我正在尝试在 python 2.6 中获取线程 ID 或名称我遵循示例但我收到错误,例如全局名称“currentThread”未定义全局名称“current_thread”未定义
(I tried both currentThread and current_thread)
(我尝试了 currentThread 和 current_thread)
Here is my code :
这是我的代码:
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
UPDATE: I fixed the error by the hint Mata gave I should have imported current_thread() too.
更新:我通过 Mata 给出的提示修复了错误,我也应该导入 current_thread()。
from threading import Thread,current_thread
采纳答案by mata
You haven't imported threading
, only Thread
.
你没有导入threading
,只有Thread
.
Either import threading
, or import current_thread
directly:
要么 import 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()
回答by Saurabh
This will work
这将工作
from threading import Thread, current_thread
def do_work(item):
print current_thread().name