How to Use Python micro-threads in Stackless

Source: Internet
Author: User

We need to constantly learn how to use Python micro-threads, and some problems have been plaguing us. Let's take a detailed look at how to solve the technical problems and some tips. I hope you will have some gains.

Using Stackless Python's built-in module stackless can also complete multi-threaded programming, making it easier to use. The following S_P_C.py script will rewrite the code of the front-end producer and consumer to the Stackless version, the code is more concise.

 
 
  1. #-*-Coding: UTF-8 -*-
  2. # File: S_P_C.py
  3. #
  4. Import stackless # import stackless Module
  5. Import Queue # import the Queue Module
  6. Def Producer (I): # define the Producer
  7. Global queue # declared as a global Queue object
  8. Queue. put (I) # add data to the queue
  9. Print 'producer ', I, 'add', I
  10. Def Consumer (): # define a Consumer
  11. Global queue
  12. I = queue. get () # retrieve data from the queue
  13. Print 'consumer', I, 'get', I
  14. Queue = Queue. Queue () # generate a queue object
  15. For I in range (10 ):
  16. Stackless. tasklet (Producer) (I) # Add a Producer task
  17. For I in range (10 ):
  18. Stackless. tasklet (Consumer) () # Add a Consumer task
  19. Stackless. run () # run the task
  20. After the script is run, the output is as follows.
  21. Producer 0 add 0
  22. Producer 1 add 1
  23. Producer 2 add 2
  24. Producer 3 add 3
  25. Producer 4 add 4
  26. Producer 5 add 5
  27. Producer 6 add 6
  28. Producer 7 add 7
  29. Producer 8 add 8
  30. Producer 9 add 9
  31. Consumer 0 get 0
  32. Consumer 1 get 1
  33. Consumer 2 get 2
  34. Consumer 3 get 3
  35. Consumer 4 get 4
  36. Consumer 5 get 5
  37. Consumer 6 get 6
  38. Consumer 7 get 7
  39. Consumer 8 get 8
  40. Consumer 9 get 9

The above is an introduction to the Python micro-thread application. I hope you will get some benefits.

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.