MULTITHREADED
PROGRAMMING
Multithreading is the ability of a process to execute multiple threads parallelly .
STARTING A NEW THREAD
MULTITHREADING EXAMPLE.
#PYTHON MULTITHREADING EXAMPLE.
#1. CALCULATE FACTORIAL USING RECURSION.
#2. CALL FACTION USING THREAD.
from _thread import start_new_thread
threadld = 1
def factorial(n):
global threadld
if n < 1: #base case
print("%s:
%d" % ("Thread",threadld))
threadld += 1
return 1
else:
returnNumber = n * factorial( n - 1) # recursive call
print(str(n) + '! = ' +
str(returnNumber))
return returnNumber
start_new_thread(factorial,(5, ))
start_new_thread(factorial,(4, ))
c = input("waiting for threads to return...\n")
#PYTHON MULTITHREADING:
PROGRAM OUTPUT
waiting for threads to return...
Thread: 1
1! = 1
2! = 2
3! = 6
4! = 24
Thread: 2
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
CREATING THREAD USING
THREADING MODULE
EXAMPLE
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID,
name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print ("Starting " + self.name)
print_time(self.name,
self.counter, 5)
print ("Exiting "
+ self.name)
def print_time(threadName, delay, counter):
while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
print ("%s: %s" %
(threadName, time.ctime(time.time())))
counter -= 1
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
print ("Exiting Main Thread")
WHEN THE ABOVE CODE IS
EXECUTED, IT PRODUCES THE FOLLOWING RESULT
>>>
Starting Thread-1Starting Thread-2Exiting Main
Thread
>>> Thread-1: Fri Jun 23 17:54:55 2023
Thread-2: Fri Jun 23 17:54:56 2023
Thread-1: Fri Jun 23 17:54:56 2023
Thread-1: Fri Jun 23 17:54:57 2023
Thread-2: Fri Jun 23 17:54:58 2023Thread-1: Fri Jun
23 17:54:58 2023
Thread-1: Fri Jun 23 17:54:59 2023
Exiting Thread-1
Thread-2: Fri Jun 23 17:55:00 2023
Thread-2: Fri Jun 23 17:55:02 2023
Thread-2: Fri Jun 23 17:55:04 2023
Exiting Thread-2
SYNCHRONIZING THREADS:
import threading
import time
class myThread
(threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
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()
def
print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print ("%s: %s" % (threadName,
time.ctime(time.time())))
counter -= 1
threadLock =
threading.Lock()
threads = []
# Create new threads
thread1 = myThread(1,
"Thread-1", 1)
thread2 = myThread(2,
"Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
# Add threads to
thread list
threads.append(thread1)
threads.append(thread2)
# Wait for all threads
to complete
for t in threads:
t.join()
print ("Exiting
Main Thread")
Output
>>>
Starting
Thread-1Starting Thread-2
Thread-1:
Fri Jun 23 17:57:28 2023
Thread-1:
Fri Jun 23 17:57:29 2023
Thread-1:
Fri Jun 23 17:57:30 2023
Thread-2:
Fri Jun 23 17:57:32 2023
Thread-2:
Fri Jun 23 17:57:34 2023
Thread-2:
Fri Jun 23 17:57:36 2023
Exiting
Main Thread
MULTITHREAD PRIORITY QUEUE
import queue
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID,
name, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.q = q
def run(self):
print ("Starting
" + self.name)
process_data(self.name,
self.q)
print ("Exiting "
+ self.name)
def process_data(threadName, q):
while not exitFlag:
queueLock.acquire()
if not workQueue.empty():
data = q.get()
queueLock.release()
print ("%s
processing %s" % (threadName, data))
else:
queueLock.release()
time.sleep(1)
threadList = ["Thread-1", "Thread-2",
"Thread-3"]
nameList = ["One", "Two", "Three",
"Four", "Five"]
queueLock = threading.Lock()
workQueue = queue.Queue(10)
threads = []
threadID = 1
# Create new threads
for tName in threadList:
thread = myThread(threadID,
tName, workQueue)
thread.start()
threads.append(thread)
threadID += 1
# Fill the queue
queueLock.acquire()
for word in nameList:
workQueue.put(word)
queueLock.release()
# Wait for queue to empty
while not workQueue.empty():
pass
# Notify threads it's time to exit
exitFlag = 1
# Wait for all threads to complete
for t in threads:
t.join()
print ("Exiting Main Thread")
Output
>>>
Starting Thread-2Starting Thread-1
Starting Thread-3Thread-1 processing OneThread-2 processing Two
Thread-3 processing ThreeThread-1 processing FourThread-2 processing
Five
Exiting Thread-3Exiting Thread-1Exiting Thread-2
Exiting Main Thread
>>>
0 comments:
Post a Comment