16
Threads

Threads. Sequential control Sequential programs: begin execute end At any time, there is a single point of execution Threads: also structured as begin

Embed Size (px)

Citation preview

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Example

area_client.py area_server.py