Tuesday, 7 February 2017

SCHEDULING IN PYTHON

Among multiple thread which thread has to start the execution first and for how much time that thread has to execute. After allocated time is over which thread has to continue the execution next comes under Scheduling. Scheduling is a dynamic process.

Example –
import threading
import time
flag = 0
class Thread1 (threading.Thread):
    def __init__(self, id, name, count):
        threading.Thread.__init__(self)
        self.id = id
        self.name = name
        self.count = count
    def run(self):
        print "Starting " + self.name
        print_time(self.name, self.count, 5)
        print "Exiting " + self.name
def print_time(tname, delay, count):
    while count:
        if flag:
            tname.exit()
        time.sleep(delay)
        print "%s: %s" % (tname, time.ctime(time.time()))
        count -= 1
t1 = Thread1(1, "Thread-1", 1)
t2 = Thread1(2, "Thread-2", 2)
t1.start()
t2.start()
print "Exiting Main Thread"

Output –
Starting Thread-1
Starting Thread-2
Exiting Main Thread
Thread-1: Tue Feb 07 16:41:57 2017
Thread-2: Tue Feb 07 16:41:58 2017
Thread-1: Tue Feb 07 16:41:58 2017
Thread-1: Tue Feb 07 16:41:59 2017
Thread-2: Tue Feb 07 16:42:00 2017
Thread-1: Tue Feb 07 16:42:00 2017
Thread-1: Tue Feb 07 16:42:01 2017
Exiting Thread-1
Thread-2: Tue Feb 07 16:42:02 2017
Thread-2: Tue Feb 07 16:42:04 2017
Thread-2: Tue Feb 07 16:42:06 2017
Exiting Thread-2

No comments:

Post a Comment