Multithreading in Python
Code
In computer architecture, multithreading is the ability of a central processing unit to provide multiple threads of execution concurrently, supported by the operating system. This approach differs from multiprocessing.
Multitasking is of two types: Processor-based and thread-based. Processor-based multitasking is totally managed by the OS, however multitasking through multithreading can be controlled by the programmer to some extent.
The concept of multi-threading needs a proper understanding of these two terms – a process and a thread. A process is a program being executed. A process can be further divided into independent units known as threads.
A thread is like a small light-weight process within a process. Or we can say a collection of threads is what is known as a process.
import logging
import threading
import time
def thread_function1(name):
print("Thread {}: starting \n".format(name))
time.sleep(5)
print("Thread {}: finishing \n".format(name))
def thread_function2(name):
print("Thread {}: starting \n".format(name))
time.sleep(3)
print("Thread {}: finishing \n".format(name))
if __name__ == "__main__":
print("Main : before creating thread \n")
x = threading.Thread(target=thread_function1, args=(1,))
y = threading.Thread(target=thread_function2, args=(2,))
print("Main : before running thread \n")
x.start()
y.start()
print("Main : wait for the thread to finish \n")
x.join()
print("Main : all done \n")
Comments
Post a Comment