Python threading Knowledge re-learning f---queue synchronization

Source: Internet
Author: User

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

A synchronized, thread-safe queue class is provided in the Python queue module, including FIFO (first-in, first-out) queue Queue,lifo (back-in-first-out) queue Lifoqueue, and priority queue priorityqueue. These queues implement the lock primitive and can be used directly in multiple threads. Queues can be used for synchronization between threads.

#!/usr/bin/env python#-*-coding:utf-8-*-ImportThreadingImport Time fromQueueImportQueueclassProducer (Threading. Thread):defRun (self):GlobalQueue Count=0 whileTrue: forIinchRange (100):                ifQueue.qsize () > 1000:                    Pass                Else: Count+ = 1msg='Build Product'+Str (count) queue.put (count)Printmsg Time.sleep (1)classConsumer (Threading. Thread):defRun (self):GlobalQueue whileTrue: forIinchRange (3):                ifQueue.qsize () < 100:                    Pass                Else: Msg= +'consumption of'+Queue.get ()Printmsg Time.sleep (1) Queue=Queue ()defTest (): forIinchRange (500): Queue.put ('Initial Product'+str (i)) forIinchRange (2): P=Producer () P.start ( ) forIinchRange (5): C=Consumer () C.start ( )if __name__=='__main__': Test ()

Python threading Knowledge re-learning f---queue synchronization

Related Article

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: 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.