How to do it...

The steps involved are as follows:

  1. We defined the MyThreadClass class, which we can use to create all the threads we want. Each thread of this type will be characterized by the operations defined in the run method, which, in this simple example, limits itself to printing a string at the beginning and at the end of its execution:
import time
import os
from random import randint
from threading import Thread

class MyThreadClass (Thread):
  1. Furthermore, in the __init__ method, we have specified two initialization parameters, respectively, name and duration, that will be used in the run method:
def __init__(self, name, duration):
Thread.__init__(self)
self.name = name
self.duration = duration

def run(self):
print ("---> " + self.name +
" running, belonging to process ID "
+ str(os.getpid()) + " ")
time.sleep(self.duration)
print ("---> " + self.name + " over ")
  1. These parameters will then be set during the creation of the thread. In particular, the duration parameter is computed using the randint function that outputs a random integer between 1 and 10. Starting from the definition of MyThreadClass, let's see how to instantiate more threads, as follows:
def main():

start_time = time.time()

# Thread Creation
thread1 = MyThreadClass("Thread#1 ", randint(1,10))
thread2 = MyThreadClass("Thread#2 ", randint(1,10))
thread3 = MyThreadClass("Thread#3 ", randint(1,10))
thread4 = MyThreadClass("Thread#4 ", randint(1,10))
thread5 = MyThreadClass("Thread#5 ", randint(1,10))
thread6 = MyThreadClass("Thread#6 ", randint(1,10))
thread7 = MyThreadClass("Thread#7 ", randint(1,10))
thread8 = MyThreadClass("Thread#8 ", randint(1,10))
thread9 = MyThreadClass("Thread#9 ", randint(1,10))

# Thread Running
thread1.start()
thread2.start()
thread3.start()
thread4.start()
thread5.start()
thread6.start()
thread7.start()
thread8.start()
thread9.start()

# Thread joining
thread1.join()
thread2.join()
thread3.join()
thread4.join()
thread5.join()
thread6.join()
thread7.join()
thread8.join()
thread9.join()

# End
print("End")

#Execution Time
print("--- %s seconds ---" % (time.time() - start_time))

if __name__ == "__main__":
main()
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.61.223