Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get thread ID or name in python 2.6

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

(I tried both currentThread and 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.

from threading import Thread,current_thread
like image 590
Medya Gh Avatar asked Jul 17 '13 18:07

Medya Gh


People also ask

How do I get the thread ID in Python?

In Python 3.3+, you can use threading. get_ident() function to obtain the thread ID of a thread. threading. get_ident() returns the thread ID of the current thread.

How do I find my current thread ID?

In the run() method, we use the currentThread(). getName() method to get the name of the current thread that has invoked the run() method. We use the currentThread(). getId() method to get the id of the current thread that has invoked the run() method.

How do I find the number of active threads in Python?

In Python, the method threading. active_co unt() from the threading module is used to count the currently active or running threads.

What is thread local in Python?

Thread-local data is data whose values are thread specific. To manage thread-local data, just create an instance of local (or a subclass) and store attributes on it: mydata = threading.local() mydata.x = 1. The instance's values will be different for separate threads.


2 Answers

You haven't imported threading, only Thread.

Either import threading, or import current_thread directly:

1 import Queue
2 from threading import Thread, current_thread
3
4 def do_work(item):
5         try:
6                 print current_thread()
like image 158
mata Avatar answered Oct 28 '22 03:10

mata


This will work

from threading import Thread, current_thread

    def do_work(item):
       print current_thread().name
like image 20
Saurabh Avatar answered Oct 28 '22 03:10

Saurabh