Thread Module-python multithreaded programming

Source: Internet
Author: User

Thread Module

* Note: Thread is not recommended for multithreaded programming during actual use, this document is only for learning (or familiarity) multithreading.

The thread module provides basic synchronization data structures in addition to derived threads, called Lock Objects (also called Yuri, mutexes, mutexes, and binary semaphores).

Common thread functions and methods for LockType lock objects:

Functions/Methods Description
Functions of the Thread module
Start_new_thread (function, args, kwargs=none) Derives a new thread, using the given args and optional Kwargs to perform the function
Allocate_lock () Assigning LockType Lock objects
Exit () Give thread exit instruction
LockType Lock Object method
Acquire (Wait=none) Attempt to get lock object
Locked () Returns true if the lock object is acquired, otherwise returns flase
Release () Release lock

For a simple example using the thread module, the code is as follows (mtsleepa.py):

1 ImportThread2  fromTimeImportSleep, CTime3 ?4 defloop0 ():5     Print 'start loop 0 at:', CTime ()6Sleep (4)7     Print 'Loop 0 done at:', CTime ()8 ?9 defLoop1 ():Ten     Print 'start loop 1 at:', CTime () OneSleep (2) A     Print 'Loop 1 done at:', CTime () - ? - defMain (): the     Print 'starting at:', CTime () - Thread.start_new_thread (Loop0, ()) - Thread.start_new_thread (LOOP1, ()) -Sleep (6) +     Print 'All do at :', CTime () - ? + if __name__=='__main__': AMain ()

Output Result:

1 starting At:sun Jul 21:38:00 20182 start loop 0 At:sun Jul 21:38:00 20183  start L  OOP 1 At:sun 21:38:00 20184 Loop 1 Done at:sun Jul 21:38:02 20185 loops 0 done At:sun Jul 22 21:38:04 20186 all done At:sun Jul 22 21:38:06 2018

In the code of this script, a sleep (6) Call is added, why do you do this? This is because if we do not prevent the main thread from continuing, it will continue to execute the next statement, show "all done" and then exit, while the two threads Loop0 () and LOOP1 () will terminate directly.

For a simple example using threads and locks, the code is as follows (mtsleepb.py):

1 ImportThread2  fromTimeImportSleep, CTime3 ?4loops = [4,2]5 ?6 defLoop (Nloop, Nsec, lock):7     Print 'Start Loop', Nloop,'At :', CTime ()8 Sleep (nsec)9     Print 'Loop', Nloop,'Done at :', CTime ()TenLock.release ()#Release Lock One ? A defMain (): -     Print 'starting at:', CTime () -Locks = [] theNloops =Range (len (loops)) - ? -      forIinchNloops: -Lock = Thread.allocate_lock ()#Assigning LockType Objects +Lock.acquire ()#attempt to get lock object - Locks.append (Lock) + ? A      forIinchNloops: atThread.start_new_thread (Loop, (I, loops[i], locks[i]))#deriving a new thread -     -      forIinchNloops: -         #wait for all locks to be released after exiting the loop to continue back operation -          whileLocks[i].locked ():#True when a lock is acquired, all locks are released after Flase -             Pass in ? -     Print 'All do at :', CTime () to ? + if __name__=='__main__': -Main ()

The output is:
1 starting At:sun Jul 22:25:45 20182 start loop 1 At:start Loop Sun Jul 22:25:45 20183
   0 At:sun Jul 22:25:45 20184 Loop 1 Done at:sun Jul 22:25:47 20185 loops 0 done At:sun Jul 22 22:25:49 20186 all done At:sun Jul 22 22:25:49 2018

The main () key-related process for locking in the main () function (the first for loop) is explained:

    1. First, create a lock list by using the Thread.allocate_lock () function to get the lock object;

    2. Each lock is obtained by means of the Acquire () method (the effect of acquiring a lock is equivalent to "locking the lock");

    3. The lock is locked and added to the lock list locks;

Why not start a thread in a locked loop?

    • First, you want to synchronize threads so that all threads are finished at the same time;

    • Second, acquiring a lock takes a bit of time to avoid the thread executing too fast, and the execution ends when the lock is acquired on the front thread.

Thread Module-python multithreaded programming

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.