Python real-thread programming thread module

Source: Internet
Author: User

In Python, in addition to being able to implement multithreading by inheriting the Threading.thread class, you can also invoke the Start_new_thread () function in the thread module to produce a new thread, as follows

Import time, Thread def timer (): Print (' hello ') def test (): To I in range (0): Thread.start_new_thread (Timer, ()) If _ _name__== ' __main__ ': Test () Time.sleep (10)

Or

Import time, Thread def timer (Name=none, Group=none): Print (' name: ' + name + ', Group: ' + Group ') def Test (): For I in RA Nge (0): Thread.start_new_thread (Timer, (' thread ' + str (i), ' group ' + str (i)) if __name__== ' __main__ ': Test () Time.sle EP (10)

This is the Thread.start_new_thread (Function,args[,kwargs]) function prototype, where the function argument is the thread that you want to call; args is the argument that passes to your thread function, he must be a tuple type , and Kwargs is an optional parameter. The end of a thread generally relies on the natural end of the thread function, or it can be called thread.exit () in a thread function, and he throws Systemexit exception to exit the thread.

Let's take a look at the lock mechanism in thread, as follows two pieces of code:

Code A

Import time, thread count = 0 def test (): Global count of I in range (0, 10000): Count + = 1 for i in range (0): Thread. Start_new_thread (Test, ()) Time.sleep (5) Print count

Code two

Import time, thread count = 0 lock = thread.allocate_lock () def test (): Global count, lock Lock.acquire () to I in range (0 , 10000): Count = 1 lock.release () for I in range (0): Thread.start_new_thread (Test, ()) Time.sleep (5) Print count

The value in code one does not use the lock mechanism, so multithreading simultaneously accesses the global count variable, causing the final count result to be not 10000*10, and in code two the lock is used to ensure that only one thread at a time can modify the value of count. So the end result is 10000*10.

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.