Upload
hope-fisher
View
213
Download
0
Embed Size (px)
Citation preview
Threads
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
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
Concurrent execution on a multi-processor computer
Processor 2
Processor 1
Thread 1
Thread 2
Concurrent execution on a single-processor computer
Thread 1
Thread 2
Time slice
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.
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
Thread in python Threading provides a class Thread Thread class methods
run() start() join() getName() setName() is_alive() isDaemon
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:
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
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
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
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)
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
server
Client 1
Client n
…
radius
radius
area
area
Example
area_client.py area_server.py