Code Explanation:
1️⃣ Importing the Module
import threading
Explanation
Imports the threading module.
Enables creation and management of multiple threads.
2️⃣ Creating an Empty List
threads = []
Explanation
A list named threads is created.
It will store all thread objects so we can later wait for them using join().
3️⃣ Starting the Loop
for i in range(3):
Explanation
Loop runs 3 times.
Values of i:
0, 1, 2
4️⃣ Creating the Thread (Important)
t = threading.Thread(target=lambda: print(i))
Explanation
A new thread is created.
target=lambda: print(i) means:
Each thread will execute a lambda function that prints i.
⚠️ Critical Concept: Late Binding
The lambda does NOT capture the value of i at that moment.
Instead, it captures the reference to variable i.
By the time threads execute, loop has finished → i = 2.
๐ So all threads will use the same final value of i.
5️⃣ Storing the Thread
threads.append(t)
Explanation
Thread is added to the list.
This helps later to join all threads.
6️⃣ Starting the Thread
t.start()
Explanation
Starts execution of the thread.
The lambda function will run concurrently.
7️⃣ Joining All Threads
for t in threads:
t.join()
Explanation
Ensures the main program waits for all threads to finish.
Prevents premature program exit.
๐ค Final Output
2
2
2

0 Comments:
Post a Comment