Python multi-thread programming (1) -- thread Module

Source: Internet
Author: User

Python provides two modules to support multi-threaded programming: thread and threading.

Thread module functions

Function

Description

Start_new_thread (function, args, kwargs = None)

Generate a new thread and use the specified parameter and optional kwargs to call the function.

Allocate_lock ()

Allocate a Lock Object of the LockType (note that the lock has not been obtained yet)

Exit ()

Exit thread

Functions of LockType lock objects

Acquire (wait = None)

Try to get the Lock Object

Locked ()

If the Lock Object is obtained, True is returned. Otherwise, False is returned.

Release ()

Release lock

Next, use the thread module to write multithreading.

# Coding: utf-8import threadfrom time import sleep, ctimedef loop0 (): print 'loop0 start at: ', ctime () print 'loop0 pending 4s' sleep (4) print 'loop0 done at: ', ctime () def loop1 (): print 'loop1 start at:', ctime () print 'loop1 pending 2 seconds 'sleep (2) print 'loop1 done at: ', ctime () def main (): print 'main thread start! 'Thread. start_new_thread (loop0, () thread. start_new_thread (loop1, () sleep (6) # main thread sleep waiting for the sub-thread to end print 'all done at: ', ctime () if _ name _ = '_ main _': main ()

Running result:


The running results of the following code are all like this and will not be given.

I believe everyone can see comments. The disadvantage of this method is that the main thread needs to sleep for a period of time and waits until all the sub-threads end. Otherwise, if the main thread ends, the sub-thread ends. However, it is difficult to determine how long the sub-thread will run.

Next we will look at the second method. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Authorization + authorization + zzM3Ls/ahozwvcD4KPHA + authorization/fs8zE2KO/ttTT2sO/0ru49tfTz9 + authorization/LzTy/authorization/fs8y1xLzTy/authorization + zb/authorization Ozwvc3ryb25np1_vcd4kpha + v7S + fill = "brush: java;"> # coding: utf-8import threadfrom time import sleep, ctimeloops = [4, 2] def loop (nloop, nsec, lock ): print 'loop ', nloop, 'start at:', ctime () print 'loop % d pending % d Second '% (nloop, nsec) sleep (nsec) print 'loop ', nloop, 'done at:', ctime () lock. release () def main (): print 'main thread start! 'Locks = [] # lock list 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 # The Master thread checks the lock status of each subthread. print 'all done at: ', ctime () if _ name _ = '_ main _': main ()

In fact, we do not recommend using the thread module. First, the higher level threading module is more advanced, and the support for threads is more complete. In addition, the attributes in the thread module may conflict with threading. Second, there is only one synchronization primitive for low-level thread modules, while there are many threading modules.

Another reason is that using thread has no control over when your process should end. When the main thread ends, all threads will be forced to end, no warning or normal cleanup. However, the threading module ensures that important sub-threads exit before exiting the process.

However, if you want to access the underlying structure of the thread, you may need to use the thread module.

In the next article, we will show how to use the threading module.

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.