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.
- #-*-Coding: UTF-8 -*-
- # File: S_P_C.py
- #
- Import stackless # import stackless Module
- Import Queue # import the Queue Module
- Def Producer (I): # define the Producer
- Global queue # declared as a global Queue object
- Queue. put (I) # add data to the queue
- Print 'producer ', I, 'add', I
- Def Consumer (): # define a Consumer
- Global queue
- I = queue. get () # retrieve data from the queue
- Print 'consumer', I, 'get', I
- Queue = Queue. Queue () # generate a queue object
- For I in range (10 ):
- Stackless. tasklet (Producer) (I) # Add a Producer task
- For I in range (10 ):
- Stackless. tasklet (Consumer) () # Add a Consumer task
- Stackless. run () # run the task
- After the script is run, the output is as follows.
- Producer 0 add 0
- Producer 1 add 1
- Producer 2 add 2
- Producer 3 add 3
- Producer 4 add 4
- Producer 5 add 5
- Producer 6 add 6
- Producer 7 add 7
- Producer 8 add 8
- Producer 9 add 9
- Consumer 0 get 0
- Consumer 1 get 1
- Consumer 2 get 2
- Consumer 3 get 3
- Consumer 4 get 4
- Consumer 5 get 5
- Consumer 6 get 6
- Consumer 7 get 7
- Consumer 8 get 8
- Consumer 9 get 9
The above is an introduction to the Python micro-thread application. I hope you will get some benefits.