1
from threading import *

def myfunc(i,name):
    print("This is " + str(name))

for i in range(4):
    name = current_thread().name
    t = Thread(target=myfunc, args=(i,name,))
    t.start()

current_thread().getName() also gives same results.I was wondering is this the way it works or is it running the same thread,so it is passing the the name MainThread?


Output :
This is MainThread
This is MainThread
This is MainThread
This is MainThread

4
  • 2
    name = current_thread().name You're always checking the name of the current thread, which is the main thread. You need to check t.name. Commented Jul 26, 2016 at 18:01
  • I suppose every time it enters the loop it creates the thread and current_thread().name should return its name.why is it returning the name MainThread Commented Jul 26, 2016 at 18:05
  • 1
    You're not calling that from the threads. You're only calling it from the main thread. Commented Jul 26, 2016 at 18:05
  • okay current_thread is the thread that is running the loop right? Commented Jul 26, 2016 at 18:10

1 Answer 1

5

current_thread() always returns the thread that called current_thread(). You're repeatedly retrieving the name of the thread that's executing the loop, not the name of any of the threads that thread launches.

If you want to get the names of the threads launched in the loop, you could have them call current_thread():

import threading

def target():
    print("This is", threading.current_thread().name)

for i in range(4):
    Thread(target=target).start()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.