Python thread multithreading

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.