Use python for Thread Programming

Source: Internet
Author: User

1) Use python for Thread Programming and study how to use both threads and queues to complete thread programming in Python.

2)Queue-A Synchronized queue class

TheQueueModule implements Multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads.QueueClass in this module implements all the required locking semantics.

3) queue-a thread-safe FIFO implementation, "it can be used to pass messages or other data between producer and consumer threads safely. locking is handled for the caller, so it is simple to have as your threads as you want working with the same queue instance."
 

Therefore, queue is thread-safe for callers and can be safely called. The following is an example.

 

          #  ! /Usr/bin/ENV Python  
Import Queue
Import Threading
Import Urllib2
Import Time

Hosts = [ " Http://yahoo.com " , " Http://google.com " ," Http://amazon.com " ,
" Http://ibm.com " , " Http://apple.com " ]

Queue = queue. Queue ()

Class Threadurl (threading. Thread ):
""" Threaded URL grab """
Def _ Init __ (Self, queue ):
Threading. thread. _ Init __ (Self)
Self. Queue = queue

Def Run (Self ):
While True:
# Grabs host from queue
Host = self. queue. Get ()

# Grabs URLs of hosts and prints first 1024 bytes of page
Url = urllib2.urlopen (host)
Print URL. Read (1, 1024)

# Signals to queue job is done
Self. queue. task_done ()

Start = Time. Time ()
Def Main ():

# Spawn a pool of threads, and pass them queue instance
For I In Range (5 ):
T = threadurl (Queue)
T. setdaemon (true)
T. Start ()

# Populate queue with data
For Host In Hosts:
Queue. Put (host)

# Wait on the queue until everything has been processed
Queue. Join ()

Main ()
Print " Elapsed time: % s " % (Time. Time ()-start)

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.