In actual computer-related applications, are you having different speeds for two related asynchronous threads? In this case, python thread programming can skillfully solve related problems. The following is a detailed introduction of the article.
We often use two threads in the producer/consumer relationship to process data in a shared buffer. For example, a producer thread accepts user data into a shared buffer and waits for a consumer thread to extract and process the data. However, if the buffer is too small and the producer and consumer asynchronous threads are not at the same speed, one thread may wait for the other.
To minimize the waiting time of threads that share resources and work at the same speed, we can use a "queue" to provide additional buffers.
Create a "queue" Object
- import Queue
- myqueue = Queue.Queue(maxsize = 10)Queue.Queue
Class is the synchronization implementation of a queue. The queue length can be unlimited or limited. You can set the Queue length through the optional parameter maxsize of the Queue constructor. If maxsize is smaller than 1, the queue length is infinite. Put a value into the queue
- myqueue.put(10)
Call the put () method of the queue object to insert a project at the end of the team. Put () has two parameters. The first item is required and is the value of the inserted project. The second block is an optional parameter. The default value is 1. If the queue is empty and the block is 1, The put () method suspends the calling thread until a data unit is empty. If the block is 0, the put method will cause a Full exception. Extract A value from the queue
- myqueue.get()
Call the get () method of the queue object to delete the queue header and return a project. The optional parameter is block. The default value is 1. If the queue is empty and the block is 1, get () will suspend the calling thread until a project is available. If the block is 0, the queue will cause an Empty exception. Let's use an example to demonstrate how to use
- Queue# queue_example.py
The above content is a part of the practical application solution for Python thread programming.