Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Threads. Sequential control Sequential programs: begin execute end At any time, there is a single point of execution Threads: also structured as begin."— Presentation transcript:

1 Threads

2 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

3 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

4 Concurrent execution on a multi- processor computer Processor 2 Processor 1 Thread 1 Thread 2

5 Concurrent execution on a single-processor computer Thread 1 Thread 2 Time slice

6 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.

7 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

8 Thread in python Threading provides a class Thread Thread class methods run() start() join() getName() setName() is_alive() isDaemon

9 Structure of program The simplest approach instantiate a Thread class with a target function call start() to let it begin working. import threading def 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 Worker Output:

10 Passing arguments import 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: 0 Worker: 1 Worker: 2 Worker: 3 Worker: 4

11 Sleeping import 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: 0 Worker: 1 Worker: 2 Worker: 3 Worker: 4

12 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

13 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)

14 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

15 server Client 1 Client n … radius area

16 Example area_client.py area_server.py


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

Similar presentations


Ads by Google