Thread module in Python3 to _thread, all kinds of online posts are said not recommended novice use thread, delicious not good always try to see.
1 Import_thread2 3 defprint_num ():4 forIinchRange (100):5 Print(i)6 7 _thread.start_new_thread (Print_num, ())8 _thread.start_new_thread (Print_num, ())9 _thread.start_new_thread (Print_num, ())Ten_thread.start_new_thread (Print_num, ())
What do you suppose is the result of the operation?
There is no result ... Because the main thread didn't do anything directly it ended. The main thread exits while the child threads do not have time to run and hangs,
This means that the main line does not wait for the child thread to finish before exiting.
The lock on the bottom line has appeared.
_thread.allocate_lock () generates a lock that locks at the beginning of the thread function, unlocks at the end, and the main line determines whether to exit by judging the state of the lock.
1 Import_thread2 3 defPrint_num (Lock):#Thread Functions4 5 forIinchRange (100):6 Print(i)7 lock.release ()8 9 #Generate 5 LocksTenLocks = [] One forIinchRange (5): ALock =_thread.allocate_lock () - Lock.acquire () - Locks.append (Lock) the #Start 5 threads, one lock per person - forIinchRange (len (locks)): - _thread.start_new_thread (Print_num, (Locks[i],)) - + #The main thread monitors the status of each lock separately, knowing that all locks are not locked and exits - forIinchRange (len (locks)): + whilelocks[i].locked (): A Pass
Python thread multithreading