Parsing XML

3 downloads 309 Views 598KB Size Report
import time class MyThread(threading.Thread): def __init__(self,str): threading.Thread.__init__(self) self.name = str de
Threads

© 2008 Haim Michael 20151123

Introduction  Each thread is the execution flow of a series of commands one after the other.  We can write code that creates new threads in addition to the main one. Using additional threads we can overcome performance problems due to blocking for threads that already run in our program.  Unlike forked processes, the new threads run all together with the ones that already exist in the same process. © 2008 Haim Michael 20151123

The _thread Module  The _thread basic module provides us with the same programming interface no matter on which operating system our code runs.  When calling the start_new_thread function on this module we indirectly start a new separated thread. The function we pass over to this method will be the main function of this new thread.

© 2008 Haim Michael 20151123

The _thread Module  If the function we pass over to start_new_thread has parameters we will pass over the arguments for these parameters.

© 2008 Haim Michael 20151123

The _thread Module import _thread def do_something(thread_id): while True: print('doing something... thread id is ', thread_id) def start_program(): i= 0 while True: i += 1 _thread.start_new_thread(do_something, (i,)) if input() == 'q': break start_program()

© 2008 Haim Michael 20151123

The _thread Module

© 2008 Haim Michael 20151123

The threading Module  The threading module provides an higher level interface for the _thread module.

© 2008 Haim Michael 20151123

The Thread Class  The threading module includes the Thread class. We can easily create new thread by defining a new class that extends it, overriding the run function and make sure that our __init__ in the new class calls the __init__ function it overrides.

© 2008 Haim Michael 20151123

The Thread Class import threading import time class MyThread(threading.Thread): def __init__(self,str): threading.Thread.__init__(self) self.name = str def run(self): i = 1 while(i