Multithreaded Programming---thread module for python

Source: Internet
Author: User

1. Using the thread module (not recommended)
Common functions:
' Start_new_thread (function,args,kwargs=none) ': Create a new thread and run ' function (args) '
' Allocate_lock () ': Create lock Object Lock objects
' Exit () ': Prompt thread to exit
The function of Lock:
' Acquire (wait=none) ': Gets the lock object or waits for wait time
' Locked () ' Gets lock returns True, otherwise returns false
' Release ': Release lock
Example 1:

import threadfrom time import sleep,ctimedef loop0():    print ‘start loop 0"def main():    thread.start_new_thread(loop0,())    sleep(6)if __name__==‘__main__‘:    main()


Note: 1, although the LOOP0 does not accept parameters, but the ' start_new_thread ' in the empty tuple can not be omitted;
2. Use sleep, because the main thread will continue to run until it exits and kill all the child threads without any checking, which is one of the reasons for not recommending the use of the thread module.

Example 2:

import threadfrom time import sleep,ctimeloops=[4,2]def loop(nloop,nsec,lock):    print ‘start loop‘,nloop,‘at:‘,ctime()    lock.release()def main():    print ‘starting‘    locks=[]    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    print ‘all done‘if __name__==‘__main__‘:    main()      


Conflicts between multiple threads that prevent access to resources by sharing lock

Multithreaded Programming---thread module for python

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.