This is the example code I am using
import time
import threading
import re
def do_action():
while True:
x = threading.current_thread()
print(x)
time.sleep(60)
for _ in range(1):
threading.Thread(target=do_action).start()
The result of Print is as follows
<Thread(Thread-1, started 10160)>
I need to get only the number of the Thread which in this case is the number 1
I tried to use
thread_number = re.findall("(\d+)", x)[0]
But error occurs when using.
The 1
in the Thread-1
output is part of the default thread name generation if you don't explicitly give your thread a name. There is no guarantee that a thread will have such a number - the main thread won't, and explicitly named threads typically won't. Also, multiple threads can have the same number, if a thread is manually given a name that matches the Thread-n
pattern.
If that's the number you want, you can get it by parsing the thread's name - int(thread.name.split('-')[1])
- but it's probably not the best tool for whatever job you plan to use it for.
If you're starting a bunch of threads and they each need to use a distinct number from 1 to n for some reason, maybe work allocation or something, just pass a number to their target function:
def do_stuff(n):
# do stuff with n
threads = [threading.Thread(target=do_stuff, args=(i,)) for i in range(1, 11)]
for thread in threads:
thread.start()
Threads also have ident
and native_id
attributes, which are None
for threads that haven't been started yet and integers for threads that have started. These are identifiers that are guaranteed to be distinct for threads alive at the same time - this distinctness guarantee is process-wide for ident
and system-wide for native_id
. However, if one thread finishes before another starts, they may be assigned the same ident
or native_id
.