Python queue thread10/6/2023 ![]() ![]() There isn’t anything fancy going on in this function. Our first function, producer, is defined on lines 16-23. Then on line 12, the queue is created as a global variable. The program creates a lock on line 9 so that only one thread can use the console at the same time. We begin by defining variables that specify the number of consumer threads (line 2), the number of produce threads (line 3), and the number of messages the producer threads make (line 4). This program shows the producer / consumer pattern in action. Time.sleep(((numproducers - 1) * nummessages) + 1) Print('consumer ', idnum, ' got => ', data) ![]() # Print the data created by the producer thread # dataQueue.get() will block this thread's execution # Function called by the consumer threads # Produce 4 messages to place on the queueĭataQueue.put(''.format(idnum, msgnum)) # Create a lock so that only one thread writes to the console at a time # Specify the number of consumer and producer threads I added my own comments to the code to help explain what is happening in the program. When data becomes available, the consumer thread removes data from the Queue and does its work.īelow is an example program borrowed from Programming Python: Powerful Object-Oriented Programming that shows how to use a Queue to synchronize data between producer and consumer threads. Consumer threads are blocked by the Queue until the Queue has data for the consumer thread to read. The Queue object is a FIFO object that lets the produce thread place data on the queue. Python’s queue module provides one of many solutions. Producer and consumer threads need a way to share data. For example, the application may have a thread dedicated to crawling the web that gathers data (producer) while other threads index and store the data (consumers). A web crawler application is a use case of the producer / consumer pattern. The producer / consumer pattern is a common programming construct used in multithreaded applications where one thread acts as a producer of data while other threads consume the data.
0 Comments
Leave a Reply.AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |