Python example-Threads and queues

Source: Internet
Author: User

#!/usr/bin/python#Coding:utf-8ImportThreadingImport TimeImportQueueImportRandom#Multithreading ComprehensiondefPrint_time (threadname,delay,counter): whileCounter:time.sleep (Delay)Print "%s:%s\n"%(Threadname,time.ctime (Time.time ())) counter-=1defMain ():Print 'All start at:', Time.ctime () Threads= []     forIinchRange (5): Name='thread-%d'%i t= Threading. Thread (target=print_time,args= (name,1,3)) Threads.append (t) forJinchThreads:j.start () forKinchThreads:k.join ()Print 'All do at :', Time.ctime ()#Queue Queuing Module UnderstandingQueue = Queue.queue (10)defmain2 (): Thread1= Threading. Thread (target=producer) Thread2= Threading. Thread (target=customer) Thread1.start () Thread2.start ()defproducer (): Nums= Range (100)     whileTrue:num=Random.choice (nums)ifqueue.full ():Print 'inventory is full \ n'        Else: Queue.put (num)Print "Product%d\n"%Num Time.sleep (1)defcustomer ():#Global Queue     whileTrue:ifqueue.empty ():Print 'inventory is empty \ n'        Else: Num=Queue.get ()Print 'consumption:%d\n'%Num Time.sleep (1)#using the queue module to control the number of threads running (concurrency type)Queue =Queue.queue ()defque_init (): Lists= Range (50)     forIinchlists:queue.put (i)defprint_num (num):PrintNumdefmain3 (): Que_init () Thread_num= 10 while  notqueue.empty (): Threads= []        ifQueue.qsize () >Thread_num:threads_number=Thread_numElse: Threads_number=queue.qsize () forIinchRange (threads_number): Das=queue.get () T= Threading. Thread (target=print_num,args=(Das,)) Threads.append (t) forJinchThreads:j.start () forKinchThreads:j.join ()Print '\ n'if __name__=='__main__':    #print_time (' Thread1 ', 1,10)Main3 ()

Python example-Threads and queues

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.