Python Experiment No: 11 Implementation of Threading in python.

Aim:- Implementation of Threading in python.
Theory:-

Threading in python is used to run multiple threads (tasks, function calls) at the same time. Note that thisdoes not mean, that they are executed on different CPUs. Python threads will NOT make your program faster if it already uses 100 % CPU time, probably you then want to look into parallel programming. If you are interested in parallel programming with python, please see here. Python threads are used in cases where the execution of a task involves some waiting. One example would be interaction with a service hosted on another computer, such as a web server. Threading allows python to execute other code while waiting; this is easily simulated with the sleep function. 

Make a thread that prints numbers from 1-10, waits for 1 sec between:

import thread
import time
def loop1_10():
for i in range(1, 11):
time.sleep(1)
print(i)
thread.start_new_thread(loop1_10, ())

A Minimal Example with Object

#!/usr/bin/env python
import threading
import time
from __future__ import print_function
class MyThread(threading.Thread):
def run(self):
print("{} started!".format(self.getName())) # "Thread-x
started!"
time.sleep(1) # Pretend to work for
a second
print("{} finished!".format(self.getName())) # "Thread-x
finishsed!"
if __name__ == '__main__':
for x in range(4): # Four times...
mythread = MyThread(name = "Thread-{}".format(x + 1)) # ...Instantiate a
thread and pass a unique ID to it
mythread.start() # ...Start the threadtime.sleep(.9) # ...Wait 0.9 seconds
before starting another
This should output:
Thread-1 started!
Thread-2 started!
Thread-1 finished!
Thread-3 started!
Thread-2 finished!
Thread-4 started!
Thread-3 finished!
Thread-4 finished!


Q1) Explain syntax to create thread in python.
Q2) How to achieve thread synchronization in python.

Comments