Python multi-thread programming (7): queue Synchronization

Source: Internet
Author: User

[From] nickname: HolbrookHttp://www.cnblogs.com/holbrook/archive/2012/02/25/2368231.html

We have introduced the mutex lock and condition variable to solve the synchronization problem between threads, and used the condition variable synchronization mechanism to solve the problem between producers and consumers.

Let's consider a more complex scenario: products are different. At this time, it is not enough to record only one quantity. You also need to record the details of each product. It is easy to think of the need to use a container to record these products.

The queue module of Python provides synchronous and thread-safe queue classes, including FIFO (first-in-first-out) queue, LIFO (first-in-first-out) queue lifoqueue, and priority queue priorityqueue. These queues implement lock primitives and can be used directly in multiple threads. You can use a queue to synchronize threads.

Implement the aforementioned producer and consumer problems using FIFO queuesCodeAs follows:

 #  Encoding = UTF-8  
Import Threading
Import Time
From Queue Import Queue

Class Producer (threading. Thread ):
Def Run (Self ):
Global Queue
Count = 0
While True:
For I In Range (100 ):
If Queue. qsize ()> 1000:
Pass
Else :
Count = count + 1
MSG = ' Generate Product ' + STR (count)
Queue. Put (MSG)
Print MSG
Time. Sleep (1)

Class Consumer (threading. Thread ):
Def Run (Self ):
Global Queue
While True:
For I In Range (3 ):
If Queue. qsize () <100:
Pass
Else :
MSG = self. Name + ' Consumed ' + Queue. Get ()
Print MSG
Time. Sleep (1)

Queue = Queue ()


Def Test ():
For I In Range (500 ):
Queue. Put ( ' Initial Product ' + STR (I ))
For I In Range (2 ):
P = producer ()
P. Start ()
For I In Range (5 ):
C = Consumer ()
C. Start ()
If _ Name __ = ' _ Main __ ' :
Test ()

 

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.