Unit-3 Multithreading
Unit-3 Multithreading
Unit-3 Multithreading
Outcomes:
• Different ways of achieving multitasking.
• Difference between Multithreading and
Multiprocessing.
• Create threads in Python using different modules.
• Different methods available in threading
modules.
Multithreading
Multitasking
• Multitasking is a process of executing multiple
tasks simultaneously.
• We use multitasking to utilize the CPU.
Multitasking can be achieved by two ways:
• Process-based Multitasking(Multiprocessing)
• Thread-based Multitasking(Multithreading)
1) Process-based Multitasking (Multiprocessing)
Kernel Threads are a part of the operating system, while the User-space threads are
not implemented in the kernel.
There are two modules which support the usage of threads in Python3 −
• _thread
• Threading
• The thread module has been "deprecated" (not recommended) for quite a long
time. Users are encouraged to use the threading module instead.
• Hence, in Python 3, the module "thread" is not available anymore. However, it has
been renamed to "_thread" for backwards compatibilities in Python3.
Starting a New Thread
Syntax:
_thread.start_new_thread ( function, args[, kwargs] )
• This method call enables a fast and efficient way to
create new threads in both Linux and Windows.
• The method call returns immediately and the child
thread starts and calls function with the passed list
of args.
• When the function returns, the thread terminates.
• Here, args is a tuple of arguments; use an empty
tuple to call function without passing any arguments.
• kwargs is an optional dictionary of keyword
arguments.
Example
import _thread
import time
# Define a function for the thread
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print ("%s: %s" % ( threadName, time.ctime(time.time()) ))
# Create two threads as follows
try:
_thread.start_new_thread( print_time, ("Thread-1", 2, ) )
_thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print ("Error: unable to start thread")
while 1:
pass
Sample Output
def run(self):
print ("Starting " + self.name)
# Get lock to synchronize threads
threadLock.acquire()
print_time(self.name, self.counter, 3)
# Free lock to release next thread
threadLock.release()
threadLock = threading.Lock()
threads = []
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2