![Page 1: Threads. Sequential control Sequential programs: begin execute end At any time, there is a single point of execution Threads: also structured as begin](https://reader036.vdocument.in/reader036/viewer/2022083007/56649e805503460f94b84778/html5/thumbnails/1.jpg)
Threads
![Page 2: Threads. Sequential control Sequential programs: begin execute end At any time, there is a single point of execution Threads: also structured as begin](https://reader036.vdocument.in/reader036/viewer/2022083007/56649e805503460f94b84778/html5/thumbnails/2.jpg)
Sequential control
Sequential programs: begin execute end At any time, there is a single point of execution Threads: also structured as begin execute end However, threads are NOT programs – they run
within a program All threads within a program
Are sequential processes Run “at the same time” Perform different tasks
![Page 3: Threads. Sequential control Sequential programs: begin execute end At any time, there is a single point of execution Threads: also structured as begin](https://reader036.vdocument.in/reader036/viewer/2022083007/56649e805503460f94b84778/html5/thumbnails/3.jpg)
Threads Multiple threads within a process share the
same data space with the main thread share information easily communicate with each other more easily than if they
were separate processes.
Threads are “light-weight processes” do not require much memory overhead; cheaper than processes.
Threads run independently and concurrently
![Page 4: Threads. Sequential control Sequential programs: begin execute end At any time, there is a single point of execution Threads: also structured as begin](https://reader036.vdocument.in/reader036/viewer/2022083007/56649e805503460f94b84778/html5/thumbnails/4.jpg)
Concurrent execution on a multi-processor computer
Processor 2
Processor 1
Thread 1
Thread 2
![Page 5: Threads. Sequential control Sequential programs: begin execute end At any time, there is a single point of execution Threads: also structured as begin](https://reader036.vdocument.in/reader036/viewer/2022083007/56649e805503460f94b84778/html5/thumbnails/5.jpg)
Concurrent execution on a single-processor computer
Thread 1
Thread 2
Time slice
![Page 6: Threads. Sequential control Sequential programs: begin execute end At any time, there is a single point of execution Threads: also structured as begin](https://reader036.vdocument.in/reader036/viewer/2022083007/56649e805503460f94b84778/html5/thumbnails/6.jpg)
Execution
A thread has a beginning, an execution sequence, and a conclusion. has an instruction pointer that keeps track of
where within its context it is currently running. It can be pre-empted (interrupted) It can temporarily be put on hold (also known
as sleeping) while other threads are running - this is called yielding.
![Page 7: Threads. Sequential control Sequential programs: begin execute end At any time, there is a single point of execution Threads: also structured as begin](https://reader036.vdocument.in/reader036/viewer/2022083007/56649e805503460f94b84778/html5/thumbnails/7.jpg)
Threads in python
python provides language-level support for threads
There are two modules _thread a low level thread implementation threading a high-level thread interface
Three ways to implement threads Create a Thread instance, passing in a function Create a Thread instance, passing in a class Subclass Thread and create subclass instance
![Page 8: Threads. Sequential control Sequential programs: begin execute end At any time, there is a single point of execution Threads: also structured as begin](https://reader036.vdocument.in/reader036/viewer/2022083007/56649e805503460f94b84778/html5/thumbnails/8.jpg)
Thread in python Threading provides a class Thread Thread class methods
run() start() join() getName() setName() is_alive() isDaemon
![Page 9: Threads. Sequential control Sequential programs: begin execute end At any time, there is a single point of execution Threads: also structured as begin](https://reader036.vdocument.in/reader036/viewer/2022083007/56649e805503460f94b84778/html5/thumbnails/9.jpg)
Structure of program
The simplest approach instantiate a Thread class with a target function call start() to let it begin working.
import threadingdef worker(): """thread worker function""" print 'Worker' return
threads = []for i in range(5): t = threading.Thread(target=worker) threads.append(t) t.start()
$ python threading_simple.py
WorkerWorkerWorkerWorkerWorker
Output:
![Page 10: Threads. Sequential control Sequential programs: begin execute end At any time, there is a single point of execution Threads: also structured as begin](https://reader036.vdocument.in/reader036/viewer/2022083007/56649e805503460f94b84778/html5/thumbnails/10.jpg)
Passing argumentsimport threading
def worker(num):
"""thread worker function"""
print 'Worker: %s' % num
return
threads = []
for i in range(5):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
$ python -u threading_simpleargs.py
Worker: 0Worker: 1Worker: 2Worker: 3Worker: 4
![Page 11: Threads. Sequential control Sequential programs: begin execute end At any time, there is a single point of execution Threads: also structured as begin](https://reader036.vdocument.in/reader036/viewer/2022083007/56649e805503460f94b84778/html5/thumbnails/11.jpg)
Sleepingimport threading
import time
def worker(num):
"""thread worker function""”
time.sleep(1)
print 'Worker: %s' % num
return
threads = []
for i in range(5):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
$ python -u threading_simpleargs.py
Worker: 0Worker: 1Worker: 2Worker: 3Worker: 4
![Page 12: Threads. Sequential control Sequential programs: begin execute end At any time, there is a single point of execution Threads: also structured as begin](https://reader036.vdocument.in/reader036/viewer/2022083007/56649e805503460f94b84778/html5/thumbnails/12.jpg)
Example 3 (with classes ) import threading
import time
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 finished!"
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 thread
time.sleep(.9) # ...Wait 0.9 seconds before starting another
![Page 13: Threads. Sequential control Sequential programs: begin execute end At any time, there is a single point of execution Threads: also structured as begin](https://reader036.vdocument.in/reader036/viewer/2022083007/56649e805503460f94b84778/html5/thumbnails/13.jpg)
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: thread.exit() time.sleep(delay) print ("%s: %s" % (threadName, time.ctime(time.time()))) counter -= 1
def main(): # 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”)
main()
Example 4 (classes)
![Page 14: Threads. Sequential control Sequential programs: begin execute end At any time, there is a single point of execution Threads: also structured as begin](https://reader036.vdocument.in/reader036/viewer/2022083007/56649e805503460f94b84778/html5/thumbnails/14.jpg)
Threads for socket communication In the networked program for calculating the
area of a circle we want to modify the program so that any number of clients may connect to the server and request an area calculation
“Round robin” approach not best Clients not communicating with each other Service is totally independent for each At any time, any number of clients may connect or
disconnect
![Page 15: Threads. Sequential control Sequential programs: begin execute end At any time, there is a single point of execution Threads: also structured as begin](https://reader036.vdocument.in/reader036/viewer/2022083007/56649e805503460f94b84778/html5/thumbnails/15.jpg)
server
Client 1
Client n
…
radius
radius
area
area
![Page 16: Threads. Sequential control Sequential programs: begin execute end At any time, there is a single point of execution Threads: also structured as begin](https://reader036.vdocument.in/reader036/viewer/2022083007/56649e805503460f94b84778/html5/thumbnails/16.jpg)
Example
area_client.py area_server.py