1. Using the thread module (not recommended)
Common functions:
' Start_new_thread (function,args,kwargs=none) ': Create a new thread and run ' function (args) '
' Allocate_lock () ': Create lock Object Lock objects
' Exit () ': Prompt thread to exit
The function of Lock:
' Acquire (wait=none) ': Gets the lock object or waits for wait time
' Locked () ' Gets lock returns True, otherwise returns false
' Release ': Release lock
Example 1:
import threadfrom time import sleep,ctimedef loop0(): print ‘start loop 0"def main(): thread.start_new_thread(loop0,()) sleep(6)if __name__==‘__main__‘: main()
Note: 1, although the LOOP0 does not accept parameters, but the ' start_new_thread ' in the empty tuple can not be omitted;
2. Use sleep, because the main thread will continue to run until it exits and kill all the child threads without any checking, which is one of the reasons for not recommending the use of the thread module.
Example 2:
import threadfrom time import sleep,ctimeloops=[4,2]def loop(nloop,nsec,lock): print ‘start loop‘,nloop,‘at:‘,ctime() lock.release()def main(): print ‘starting‘ locks=[] nloops = range(len(loops)) for i in nloops: lock=thread.allocate_lock() lock.acquire() locks.append(lock) for i in nloops: thread.start_new_thread(loop,(i,loops[i],locks[i]) for i in nloops: while locks[i].locked(): pass print ‘all done‘if __name__==‘__main__‘: main()
Conflicts between multiple threads that prevent access to resources by sharing lock
Multithreaded Programming---thread module for python