How can you assign a name to a thread in Python?

How can you assign a name to a thread in Python?

a) By using the name attribute of the Thread class
b) By using the set_name() method
c) By passing the name parameter to the Thread constructor
d) Both a and c

Answer:

d) Both a and c

Explanation:

You can assign a name to a thread in Python either by passing the name parameter to the Thread constructor or by setting the name attribute of the thread object after it is created.

import threading

def thread_task():
    print(f"Thread {threading.current_thread().name} is running")

# Creating a thread with a name
thread = threading.Thread(target=thread_task, name="MyThread")
thread.start()

# Alternatively, setting the thread's name
thread.name = "NewThreadName"
thread.start()

In this example, the thread is named “MyThread” during its creation. The name can also be changed later by setting the name attribute directly.

Naming threads can be helpful for debugging and logging purposes, as it allows you to easily identify and track specific threads in your application.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top