How to create and start a thread in multithreading using threading module in Python with example?

We are using threading module to achieve multithreading in Python. Let's take a problem first then solve that problem with multithreading.

Example: 

Without using Multithreading concept.

print("hey eagle eye! am start")

print("running.")

def complex_code1():
  for i in range(1, 100):
    print("heyy! i am complex code 1 running..")

def complex_code2():
  for i in range(1, 100):
    print("heyy! i am complex code 2 running..")

complex_code1()
complex_code2()  

print("i am waitting for you..!")

print("i am importent code.")

print("done!")

Output:

hey eagle eye! am start
running.
heyy! i am complex code 1 running..
heyy! i am complex code 1 running..
heyy! i am complex code 1 running..

# this block run 100 times

heyy! i am complex code 1 running..
heyy! i am complex code 1 running..
heyy! i am complex code 1 running..
heyy! i am complex code 2 running..
heyy! i am complex code 2 running..

# this block run 100 times

heyy! i am complex code 2 running..
heyy! i am complex code 2 running..
i am waitting for you..!
i am importent code.
done!

 

Let's solve this problem using the multithreading concept in a very simple way.

First, syntax for threading module in Python.

import threading

How to create threads in multithreading using threading module?

We create the thread using threading. Thread and inside the Thread() we pass a hyperparameter that is target. We pass a function name or if we use a based thread then pass a method name. That function holds a task that we want to execute.

Syntax:

thread_name = threading.Thread(target = function_name)

Note : you can make multiple threads according to your needs.
 

How to start a thread in multithreading using the threading module in Python?

In the threading module in Python, we have a method start() to start a thread.

Syntax:

 

thread_name.start()

 

Let's do our example now with the help of threading module in Python.

Make My functions as a thread. Now remember one thing, Threads do not start till we do not use the start method. For now, let's run the example without using run and see what happens.

Our Example now looks like:

import threading

print("hey eagle eye! am start")

print("running.")

def complex_code1():
  for i in range(1, 100):
    print("heyy! i am complex code 1 running..")

def complex_code2():
  for i in range(1, 100):
    print("heyy! i am complex code 2 running..")

thread1 = threading.Thread(target = complex_code1)
thread2 = threading.Thread(target = complex_code2)

print("i am waitting for you..!")

print("i am importent code.")

print("done!")

Output:

hey eagle eye! am start
running.
i am waitting for you..!
i am importent code.
done!

So, we see the code is working but threads are not starting. Let's start the thread now.

By doing this now, due to threading our functions or we can say complex tasks run in the background. So that our processor also gives time to the next code. 

 Our Example now looks like:

import threading

print("hey eagle eye! am start")

print("running.")

def complex_code1():
  for i in range(1, 100):
    print("heyy! i am complex code 1 running..")

def complex_code2():
  for i in range(1, 100):
    print("heyy! i am complex code 2 running..")

thread1 = threading.Thread(target = complex_code1)
thread2 = threading.Thread(target = complex_code2)

thread1.start()
thread2.start()

print("i am waitting for you..!")

print("i am importent code.")

print("done!")

Output:

hey eagle eye! am start
running.
heyy! i am complex code 1 running..
heyy! i am complex code 1 running..
heyy! i am complex code 2 running..
heyy! i am complex code 2 running..
heyy! i am complex code 1 running..
i am waitting for you..!
heyy! i am complex code 2 running..
i am importent code.
done!
heyy! i am complex code 2 running..
heyy! i am complex code 2 running..
heyy! i am complex code 2 running..
heyy! i am complex code 1 running..
heyy! i am complex code 2 running..
heyy! i am complex code 1 running..
heyy! i am complex code 1 running...
.
.

 

Now, our next lines of code do not wait for their upper lines or complex code to execute. Now all the code runs parallel. Our thread1 and thread2 run in the background and they continue executing in the background till they do not complete. Let's learn more about threading with the help of questions and answers.


 

20+ interview questions about Python’s threading module and multithreading concepts

Question 1. What is multithreading in Python?

Answer: Multithreading is a technique that allows multiple threads to run concurrently within a single process. It helps in performing I/O-bound tasks efficiently.

Example:

import threading
print("Multithreading allows concurrent execution.")

 

Question 2. How do you import the threading module in Python?

Answer: You can import it using import threading.

Example:

import threading
print("Threading module imported.")

 

Question 3. How do you create a thread in Python using the threading module?

Answer: You create a thread by instantiating the Thread class.

Example:

import threading

def task():
    print("Thread is running.")

thread = threading.Thread(target=task)
thread.start()

Output:

Thread is running.

 

Question 4. How do you pass arguments to a thread?

Answer: Use the args parameter while creating the thread.

Example:

import threading

def greet(name):
    print(f"Hello, {name}!")

thread = threading.Thread(target=greet, args=("Alice",))
thread.start()

Output:

Hello, Alice!

 

Question 5. What is the target parameter in threading?

Answer: The target parameter specifies the function to run in the thread.

Example:

import threading

def task():
    print("Target function is running.")

threading.Thread(target=task).start()

 

Question 6. Can you run multiple threads in parallel? How?

Answer: Yes, create multiple threads and start them.

Example:

import threading

def task1():
    print("Task 1 running.")

def task2():
    print("Task 2 running.")

threading.Thread(target=task1).start()
threading.Thread(target=task2).start()

Output:

Task 1 running.
Task 2 running.

 

Question 7. What is the main thread?

Answer: The main thread is the initial thread that starts when the Python program runs.

Example:

import threading
print(f"Main thread: {threading.main_thread().name}")

Output:

Main thread: MainThread

 

Question 8. How can you name a thread?

Answer: Use the name parameter while creating the thread.

Example:

import threading

def task():
    print(f"Running {threading.current_thread().name}")

thread = threading.Thread(target=task, name="WorkerThread")
thread.start()

Output:

Running WorkerThread

 

Question 9. How do you get the current thread name?

Answer: Use threading.current_thread().name.

Example:

import threading
print(f"Current thread: {threading.current_thread().name}")

Output:

Current thread: MainThread

 

Question 10. How do you check if a thread is alive?

Answer: Use the is_alive() method on the thread object.

Example:

import threading

def task():
    pass

thread = threading.Thread(target=task)
thread.start()
print(f"Thread alive: {thread.is_alive()}")

 

Question 11. What is the daemon thread in Python?

Answer: A daemon thread runs in the background and is terminated when the main program exits.

Example:

import threading

def task():
    while True:
        print("Running in the background.")

thread = threading.Thread(target=task, daemon=True)
thread.start()

 

Question 12. How do you set a thread as a daemon?

Answer: Use the daemon parameter or set thread.daemon = True.

Example:

import threading

def task():
    print("Daemon thread running.")

thread = threading.Thread(target=task, daemon=True)
thread.start()

 

Question 13. What is the default name of a thread?

Answer: The default name is Thread-n where n is a number.

Example:

import threading

def task():
    print(threading.current_thread().name)

thread = threading.Thread(target=task)
thread.start()

Output:

Thread-1

 

Question 14. Can you stop a thread?

Answer: Python does not provide a direct way to stop a thread. You can use a flag to control its execution.

Example:

import threading
import time

stop_thread = False

def task():
    while not stop_thread:
        print("Thread running.")
        time.sleep(1)

thread = threading.Thread(target=task)
thread.start()

time.sleep(3)
stop_thread = True

Output:

Thread running.
Thread running.
Thread running.

 

Question 15. How can you identify a thread's ID?

Answer: Use threading.get_ident().

Example:

import threading
print(f"Thread ID: {threading.get_ident()}")

 

Question 16. How do you list all active threads?

Answer: Use threading.enumerate().

Example:

import threading
print(f"Active threads: {threading.enumerate()}")

 

Question 17. How do you control thread concurrency in Python?

Answer: You can use locks, events, or semaphores.

Example:

import threading

lock = threading.Lock()

def task():
    with lock:
        print("Task with lock.")

thread = threading.Thread(target=task)
thread.start()

 

Question 18. What is the threading.local() object?

Answer: It provides thread-local data that is specific to the thread.

Example:

import threading

data = threading.local()
data.value = 42
print(data.value)

 

Question 19. What are GIL and its impact on multithreading?

Answer: The Global Interpreter Lock (GIL) allows only one thread to execute Python bytecode at a time, limiting CPU-bound task efficiency in multithreading.

 

Question 20. How do you implement a thread-safe counter?

Answer: Use a threading.Lock.

Example:

import threading

counter = 0
lock = threading.Lock()

def increment():
    global counter
    with lock:
        counter += 1

threads = [threading.Thread(target=increment) for _ in range(10)]
for t in threads: t.start()
for t in threads: t.join()
print(f"Counter: {counter}")

Output:

Counter: 10

 

Leave a comment

You must be logged in to post a comment.

0 Comments