Python Association Libraries Gevent Learning--gevent data Structure and actual combat (iii)

Source: Internet
Author: User

Gevent Study Series The third chapter, the previous two chapters analyzed a large number of commonly used several functions of the source code and implementation principle. This chapter focuses on the actual combat, according to the official Gevent study guide, I will analyze the official given 7 data structures in turn. and give some examples of how to use them accordingly.

1. Event:

An event is an example of a gevent guide that allows us to attach an asynchronous communication between Greenlet:

Importgevent fromGevent.eventImportEvent" "illustrates the use of events" "evt=Event ()defsetter ():" "After 3 seconds, wake all threads waiting on the value of EVT" "    Print('A:hey wait for me, I has to do something') Gevent.sleep (3)    Print("Ok, I ' m done") Evt.set ()defWaiter ():" "After 3 seconds the get call would unblock" "    Print("I ' ll wait for you") evt.wait ()#Blocking    Print("It ' s about time")defMain (): Gevent.joinall ([Gevent.spawn (Setter), Gevent.spawn (Waiter), Gevent.spawn (waiter), ])if __name__=='__main__': Main ()

Here the setter and waiter have three co-processes. Analyzing the run order should be easy to understand why EVT is doing:

First callback line to run setter print str then gevent.sleep (3).

Then execute the second callback Waitter () to Evt.wait () to block and then switch, how to switch the details to be analyzed is a big wave. Anyway, it's switching.

Then executes the third callback Waitter () execution to evt.wait () and is blocked again, this time continue to execute the next callback will go back to the setter, because no one in front of him to the Hub.loop register

Then execute "OK, I'm done" OK I'm finished, run Evt.set () set flag to True.

Then the other two blocked Waitter's evt.wait () method no longer continues to block the run and ends after seeing that flag is already true.

As you can see, the event can work with several greenlet at the same time, and a master Greenlet can allow several others to wait while the operation is in place, enabling certain environments and requirements to be fulfilled.

Importgevent fromGevent.eventImportAsyncresulta=AsyncResult ()defsetter ():"""After 3 seconds set the result of a. """Gevent.sleep (3) A.set ('hello!')defWaiter ():"""After 3 seconds the get call would unblock after the setter puts a value into the AsyncResult. """    Print(A.get ()) Gevent.joinall ([Gevent.spawn (Setter), Gevent.spawn (Waiter),])

The event also has an extension AsyncResult, which can be used to pass data to each waiter when set. Get is still blocked here, but the wait is not flag, but a value or an error related more detailed API or more features can refer to document http://www.gevent.org/gevent.event.html.

2: Queue:

A queue is a sorted collection of data that has a common put / get operation, but it is implemented in a way that can be safely manipulated between greenlet.

For example, if a greenlet is taken from a queue, the item will not be fetched by other Greenlet that are executed concurrently. Can be understood to be based on the security queue between the Greenlet or the first official example:

Importgevent fromGevent.queueImportQueuetasks=Queue ()defworker (N): while  nottasks.empty (): Task=Tasks.get ()Print('Worker%s got task%s'%(n, Task)) gevent.sleep (0)Print('quitting time!')defboss (): forIinchXrange (1,25): tasks.put_nowait (i) gevent.spawn (boss). Join () Gevent.joinall ([Gevent.spawn (Worker,'Steve'), Gevent.spawn (worker,'John'), Gevent.spawn (worker,'Nancy'),])

Initializes a queue () instance first. This will first run the Boss () call Put_nowait () method to put 24 elements into the queue without blocking. Then the following sequentially from the queue to the number of consumption, the three have been named after the two different names, using the Get method in order to consume the numbers in the queue until consumption is complete.

both put and get operations have non-blocking versions, andput_nowait and get_nowait do not block, but are thrown when the operation cannot be completed Gevent.queue.Empty or gevent.queue.Full exceptions. At the same time the queue queue can support setting the maximum queue value, viewing the queue now the number of elements qsize (), whether the queue is empty (), whether the queue is full () and other APIs when used, it is best to also refer to the document: http://www.gevent.org/ gevent.queue.html

3.Group gevent documents translated into pooled pools:

To be continue .....

When I read the multiprocessing module, I'll take a look at this.

Python Association Libraries Gevent Learning--gevent data Structure and actual combat (iii)

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