Code Explanation:
๐น 1. Importing the module
import threading
This line imports the threading module.
It allows you to create and manage threads (multiple flows of execution running in parallel).
๐น 2. Initializing a variable
x = 0
A global variable x is created.
It is initialized with value 0.
This variable will be accessed and modified by the thread.
๐น 3. Defining the task function
def task():
A function named task is defined.
This function will be executed inside a separate thread.
๐น 4. Declaring global variable inside function
global x
This tells Python that x refers to the global variable, not a local one.
Without this, Python would create a local x inside the function.
๐น 5. Modifying the variable
x = x + 1
The value of x is increased by 1.
Since x is global, the change affects the original variable.
๐น 6. Creating a thread
t = threading.Thread(target=task)
A new thread t is created.
The target=task means this thread will run the task() function.
๐น 7. Starting the thread
t.start()
This starts the thread execution.
The task() function begins running concurrently.
๐น 8. Waiting for thread to finish
t.join()
This makes the main program wait until the thread finishes execution.
Ensures that task() completes before moving forward.
๐น 9. Printing the result
print(x)
After the thread finishes, the updated value of x is printed.
Output will be:
1

0 Comments:
Post a Comment