Med*_* Gh 8 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
Run Code Online (Sandbox Code Playgroud)
更新:我通过提示修复了错误Mata给了我应该导入的current_thread().
from threading import Thread,current_thread
Run Code Online (Sandbox Code Playgroud)
mat*_*ata 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()
Run Code Online (Sandbox Code Playgroud)
这将工作
from threading import Thread, current_thread
def do_work(item):
print current_thread().name
Run Code Online (Sandbox Code Playgroud)