1. Content in the threading module
-Thread: An executable thread object
-Lock: The original lock object is the same as in the thread module
-Rlock: Lock that allows a single thread to request multiple times
-Condition: Thread waits until condition is met
-Event: Wake up all waiting processes when events occur
-Semaphore: Semaphore, identifying the number of finite resources
-Timer: Timed boot thread
-Barrier: Waits for all the specified processes to come
2, daemon Threads daemon Process
If your main thread is ready to exit, and you don't care if the child thread is complete, you can set the daemon,
' Thread.daemon = True ', which indicates that the thread is used to wait for its child threads
3. Thread class
Generic: Name: Thread name; ident: Thread id; daemon: Identifies whether the thread is a daemon thread
Class method:
"Init(group=none,target=none,name=none,args= (), Kwargs={},verbose=none,daemon=none") class constructor, target is an executable function
Start (): Start execution
Run (): Defines threading functionality, typically implemented in subclasses
Join (Timeout=none): hangs until the thread that calls it ends, or waits for a timeout time
GetName (): Returns the thread name
SetName (name): Set thread name
Isalive/is_alive (): Whether the thread is still running
Example 1:
import threadingfrom time import sleep, ctimeloops = [4,2]def loop(nloop, nsec): print ‘start loop‘,nloopdef main(): print ‘starting‘ threads=[] nloops=range(len(loops)) for i in nloops: t = threading.Thread(target=loop,args=(i,loops[i]) threads.append(t) for i in nloops: thread[i].start() # start threads for i in nloops: # wait for all threads[i].join() # threads to finishif __name__ == ‘__main__‘: main()
The target can also be a callable class instance.
Example 2:
import threadingform time import sleep, ctimeloops=[4,2]class ThreadFunc(object): def __init__(self,func,args,name=‘‘): self.name=name self.func=func self.args=args def __call__(self): self.func(*self.args)def loop(nloop,nsec): print ‘start loop‘,nloopdef main(): print ‘starting‘ threads = [] nloops= range(len(loops)) for i in nloops: # create all threads t = threading.Thread( target=ThreadFunc(loop,(i,loops[i]),loop.__name__)) threads.append(t) for i in nloops: #start all threads threads.append(t) for i in nloops: #wait for completion threads[i].join() print "all done"if __name__=‘__main__‘: main()
Python multithreaded programming----Threading Module