![]() Next, the producer coroutine generates a new random value and random priority for each iteration of the task and adds them as a tuple to the queue. The producer coroutine and consumer coroutines are configured and started and the main coroutine blocks until the new coroutines terminate. Running the example first creates the shared asyncio.PriorityQueue instance. ![]() The task will iterate ten times in a loop. Producer Coroutineįirst, we can define the function to be executed by the producer coroutine. This will be helpful to the producer to know when all items have been processed so that a special shutdown signal can be sent to the consumer, called a sentinel value. This will demonstrate the priority ordering of the asyncio.PriorityQueue class.Īdditionally, the consumer will mark each item as done. The consumer will retrieve the items from the queue, block for a random fraction of a second, then report the value. ![]() The producer coroutine will run fast and populate the queue as fast as it can. ![]() We will also create a consumer coroutine that will get numbers from the queue in priority order (ascending order or lower values are higher priority) and report their values. In this example, we will create a producer coroutine that will generate ten random numbers as data and put them on the queue with a randomly determined priority. We can explore how to use the asyncio.PriorityQueue class with a worked example. For example, if the priority queue held integers, they would be kept in ascending integer values where lower values indicated higher priority.Ĭonsider if we created a priority queue and added the following three items ‘7’, ‘9’, and ‘2’.ĭownload my FREE PDF cheat sheet Example of Using an Asyncio PriorityQueue This means the priority queue works like a list that is kept sorted. Heaps are binary trees for which every parent node has a value less than or equal to any of its children. This module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm. Internally, the priority queue makes use of the heapq module that provides utilities for maintaining ordered queues using a heap data structure (a tree). The priority order is determined by their value. With a priority queue, the entries are kept sorted (using the heapq module) and the lowest valued entry is retrieved first. Specifically, the order in which items are returned by calls to get() relative to the order in which they were added via calls to put().Ī priority queue is a queue in which the order that items are retrieved from the queue is defined by an item priority. The difference between queues is the order in which items are maintained.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |