Python Multithreading knowledge-practical examples

Source: Internet
Author: User

Python multi-threaded usage scenario: IO operation, not suitable for CPU-intensive Operation task 1, multiple thread memory sharing 2, thread simultaneous modification of the same data need to lock, mutex mutex 3, recursive lock: Many locks, locks have lock 4, Python multi-threading, at the same time only the CPU is executing. To start a thread:
1 ImportThreading2 defrun (name)3     Print("run thread ....")4 5 #create Process object, target= method name, args= (parameter 1, parameter B,)6t = Threading. Thread (target=run,args=(n,))7 #Setting the daemon thread8 T.setdaemon (True)9 #Start ThreadTen T.start () One #wait for thread to end AT.jion ()

Model Quantity usage (thread pool)

1 ImportThreading2 Import Time3 4 defrun (n):5     #Locking6 Semaphore.acquire ()7     Print("look:%s"%N)8Time.sleep (0.5)9     #Release LockTen semaphore.release () One  A if __name__=="__main__": -     #allow 5 threads at a time -Semaphore = Threading. Boundedsemaphore (5) theTlist = [] -     #How many threads are set -      forIinchRange (33): -t = Threading. Thread (target=run,args=(i,)) + T.start () - tlist.append (t) +      forRinchtlist: AR.jion ()

Python Multithreading knowledge-practical examples

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.