0% found this document useful (0 votes)
123 views

Operating System Lab

The document discusses threading in Python. It covers how to create threads by subclassing threading.Thread and overriding the run() method. It also discusses various thread methods like start(), join(), isAlive() for managing threads. Examples are provided to demonstrate creating multiple threads, passing functions to threads, and ensuring threads execute sequentially using locks.

Uploaded by

Abdullah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
123 views

Operating System Lab

The document discusses threading in Python. It covers how to create threads by subclassing threading.Thread and overriding the run() method. It also discusses various thread methods like start(), join(), isAlive() for managing threads. Examples are provided to demonstrate creating multiple threads, passing functions to threads, and ensuring threads execute sequentially using locks.

Uploaded by

Abdullah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Lab 9: Threading

Objectives
to learn
1. How to create threads
2. How to manage threads

1. How to Create Threads


We have studied in class that Multiple threads within a process share the same data space with
the main thread and can therefore share information or communicate with each other more easily
than if they were separate processes. Threads sometimes called light-weight processes and they
do not require much memory overhead; they are cheaper than processes.

The methods provided by the Thread class are as follows:

 run(): The run() method is the entry point for a thread.

 start(): The start() method starts a thread by calling the run method.

 join([time]): The join() waits for threads to terminate.

 isAlive(): The isAlive() method checks whether a thread is still executing.

 getName(): The getName() method returns the name of a thread.

 setName(): The setName() method sets the name of a thread.

Steps to create a thread

1#: Import threading


2#: Create your own class
class mythread(threading.Thread)
3# Override __init__()
def __init__(self):
threading.Thread.__init__(self)
4#: override run method
Example code#1

#!/usr/bin/python

import threading
import time

class t1(threading.Thread):
count=0
def __init__(self,name):
threading.Thread.__init__(self)
self.name=name
def run(self):
time.sleep(5)
t1.count = t1.count + 1
print("count--",t1.count)

def main():
t11 = t1("T1")
t11.start()
t12 = t1("T2")
t12.start()
t13 = t1("T3")
t13.start()
t14 = t1("T4")
t14.start()
main()
2. How to Manage Threads

Python provides three concepts to implement concurrency, which are given below:
Thread : A low level module that provide basic primitives of threads.
Threading : It is a higher level interface or a top level of thread.
Multiprocessing: It provides local and remote concurrency

Threads have few basic method which provide easy thread mangemnt. Before we start threading
with queues and locks I shall discuss is_alive() and join() methods. if at any instance of time
you want to know the status in term of either thread is live or dead you can use is_alive ()
method that returns a True or False.

Example code#2

#!/usr/bin/python
import threading
import time

class MyThread(threading.Thread):

def run(self):
time.sleep(3)
return

for i in range(3):
thread = MyThread()
thread.start()
print 'thread is alive =', thread.is_alive()
thread.join()
print 'thread is alive=', thread.is_alive()

Calling function outside the Thread class: In the next Example we have created two functions.
print_table() and print_counting() one is invoked by each thread. I want to check which thread
does the particular activity first. You will see that without sleep threads are called in a specific
order and GIL (Global Interpreter Lock) just reorder the threads. Using Sleep function we can
enforce randomness efficiently or in a desired manner. To have multithreading true benefit we
have to use multiprocessing which I shall discuss in next session.
Example code#

#!/usr/bin/python5
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 +"\n"
if (self.name =="T1"):
print_table(self.name,3)
time.sleep(3)
else:
print_counting(5)
time.sleep(4)
print "Exiting " + self.name

def print_table(thread,t):
for i in range(1,5):
pr=repr(t)+"*"+repr(i)+"="+repr(t*i)+"\n"
print (pr)
def print_counting(n):
#print("exxitflag",exitFlag)
for i in range(1,n):
pr="Counting..."+repr(i)+"\n"
print (pr)
print "I am in main thread \n"
# Create new threads
thread1 = myThread(1, "T1", 1)
thread2 = myThread(2, "T2", 1)
# Start new Threads
thread1.start()
thread2.start()
print "Exiting Main Thread \n"
print "check statement \n"
Exercises

Exercise :1

1. Write python script to create three different threads belonging to different thread classes.
2. Enhance example 3 code adding few more functions to the class and then check if the
thread alive at a particular instance of time.
3. Explain the given Code
import threading
import time
import random

lock = threading.Lock ()

class MyThread1 (threading.Thread):


def run (self):
global lock
print ("Thread 1 sleeping\n")
time.sleep (random.randint(1, 10))
lock.acquire ()
print ("I should finished first")
lock.release ()

class MyThread2 (threading.Thread):


def run (self):
global lock
print ("Thread 2 sleeping\n")
time.sleep (random.randint(1, 10))
lock.acquire ()
print ("I should finish last")
lock.release ()

m1 = MyThread1 ()
m1.start ()
m2 = MyThread2 ()
m2.start ()

Exercise :2

1. Write python program to create a queue of processes(threads) and ensure that when one
process will be doing a particular activity no other thread could interrupt the thread.

You might also like