-
Notifications
You must be signed in to change notification settings - Fork 103
/
index.html
1730 lines (1461 loc) · 48.1 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script src="jquery.js"></script>
<script src="highlight.min.js"></script>
<script src="nav.js"></script>
<!-- Code Monospace Font -->
<link href='http://fonts.googleapis.com/css?family=Inconsolata' rel='stylesheet'>
<link rel="stylesheet" href="base.css">
<link rel="stylesheet" href="skeleton.css">
<link rel="stylesheet" href="layout.css">
<link rel="stylesheet" href="gevent.css">
<!-- Syntax Highlighting Theme -->
<link rel="stylesheet" href="github.min.css">
<title>Gevent Tutorial</title>
</head>
<style>
</style>
<body>
<div class="container">
<div id="sidebar" class="three columns sidebar">
<nav>
</nav>
</div>
<div class="twelve columns offset-by-three content">
<header>
<h1><span class="green">gevent</span> For the Working Python Developer</h1>
<h3 class="author">
Written by the Gevent Community
</h3>
<blockquote>
gevent is a concurrency library based around <a href="http://software.schmorp.de/pkg/libev.html">libev</a>. It provides a clean API for a variety of concurrency and network related tasks.
</blockquote>
</header>
<div class="toc">
<ul>
<li><a href="#introduction">Introduction</a><ul>
<li><a href="#contributors">Contributors</a></li>
</ul>
</li>
<li><a href="#core">Core</a><ul>
<li><a href="#greenlets">Greenlets</a></li>
<li><a href="#synchronous-asynchronous-execution">Synchronous & Asynchronous Execution</a></li>
<li><a href="#determinism">Determinism</a></li>
<li><a href="#spawning-greenlets">Spawning Greenlets</a></li>
<li><a href="#greenlet-state">Greenlet State</a></li>
<li><a href="#program-shutdown">Program Shutdown</a></li>
<li><a href="#timeouts">Timeouts</a></li>
<li><a href="#monkeypatching">Monkeypatching</a></li>
</ul>
</li>
<li><a href="#data-structures">Data Structures</a><ul>
<li><a href="#events">Events</a></li>
<li><a href="#queues">Queues</a></li>
<li><a href="#groups-and-pools">Groups and Pools</a></li>
<li><a href="#locks-and-semaphores">Locks and Semaphores</a></li>
<li><a href="#thread-locals">Thread Locals</a></li>
<li><a href="#subprocess">Subprocess</a></li>
<li><a href="#actors">Actors</a></li>
</ul>
</li>
<li><a href="#real-world-applications">Real World Applications</a><ul>
<li><a href="#gevent-zeromq">Gevent ZeroMQ</a></li>
<li><a href="#simple-servers">Simple Servers</a></li>
<li><a href="#wsgi-servers">WSGI Servers</a></li>
<li><a href="#streaming-servers">Streaming Servers</a></li>
<li><a href="#long-polling">Long Polling</a></li>
<li><a href="#websockets">Websockets</a></li>
<li><a href="#chat-server">Chat Server</a></li>
</ul>
</li>
</ul>
</div>
<h1 id="introduction">Introduction</h1>
<p>The structure of this tutorial assumes an intermediate level
knowledge of Python but not much else. No knowledge of
concurrency is expected. The goal is to give you
the tools you need to get going with gevent, help you tame
your existing concurrency problems and start writing asynchronous
applications today.</p>
<h3 id="contributors">Contributors</h3>
<p>In chronological order of contribution:
<a href="http://www.stephendiehl.com">Stephen Diehl</a>
<a href="https://github.com/jerem">Jérémy Bethmont</a>
<a href="https://github.com/sww">sww</a>
<a href="https://github.com/brunoqc">Bruno Bigras</a>
<a href="https://github.com/dripton">David Ripton</a>
<a href="https://github.com/traviscline">Travis Cline</a>
<a href="https://github.com/Lothiraldan">Boris Feld</a>
<a href="https://github.com/youngsterxyf">youngsterxyf</a>
<a href="https://github.com/ehebert">Eddie Hebert</a>
<a href="http://notmyidea.org">Alexis Metaireau</a>
<a href="https://github.com/djv">Daniel Velkov</a>
<a href="https://github.com/sww">Sean Wang</a>
<a href="https://github.com/methane">Inada Naoki</a>
<a href="https://github.com/brouberol">Balthazar Rouberol</a>
<a href="https://github.com/iepathos">Glen Baker</a>
<a href="https://gehrcke.de">Jan-Philip Gehrcke</a>
<a href="https://github.com/zr40">Matthijs van der Vleuten</a>
<a href="http://simonsblog.co.uk">Simon Hayward</a>
<a href="https://github.com/AJamesPhillips">Alexander James Phillips</a>
<a href="https://github.com/ramiro">Ramiro Morales</a>
<a href="https://github.com/djheru">Philip Damra</a>
<a href="https://github.com/fvieira">Francisco José Marques Vieira</a>
<a href="https://www.davidxia.com">David Xia</a>
<a href="https://github.com/satoru">satoru</a>
<a href="https://github.com/jsummerfield">James Summerfield</a>
<a href="https://github.com/adaszko">Adam Szkoda</a>
<a href="https://github.com/roysmith">Roy Smith</a>
<a href="https://github.com/jianbin-netskope">Jianbin Wei</a>
<a href="https://github.com/ToxicWar">Anton Larkin</a>
<a href="https://github.com/matiasherranz-santex">Matias Herranz</a>
<a href="http://www.bertera.it">Pietro Bertera</a></p>
<p>Also thanks to Denis Bilenko for writing gevent and guidance in
constructing this tutorial.</p>
<p>This is a collaborative document published under MIT license.
Have something to add? See a typo? Fork and issue a
pull request <a href="https://github.com/sdiehl/gevent-tutorial">Github</a>.
Any and all contributions are welcome.</p>
<p>This page is also <a href="http://methane.github.com/gevent-tutorial-ja">available in Japanese</a> and <a href="http://pbertera.github.io/gevent-tutorial-it/">Italian</a>.</p>
<h1 id="core">Core</h1>
<h2 id="greenlets">Greenlets</h2>
<p>The primary pattern used in gevent is the <strong>Greenlet</strong>, a
lightweight coroutine provided to Python as a C extension module.
Greenlets all run inside of the OS process for the main
program but are scheduled cooperatively.</p>
<blockquote>
<p>Only one greenlet is ever running at any given time.</p>
</blockquote>
<p>This differs from any of the real parallelism constructs provided by
<code>multiprocessing</code> or <code>threading</code> libraries which do spin processes
and POSIX threads which are scheduled by the operating system and
are truly parallel.</p>
<h2 id="synchronous-asynchronous-execution">Synchronous & Asynchronous Execution</h2>
<p>The core idea of concurrency is that a larger task can be broken down
into a collection of subtasks which are scheduled to run simultaneously
or <em>asynchronously</em>, instead of one at a time or <em>synchronously</em>. A
switch between the two subtasks is known as a <em>context switch</em>.</p>
<p>A context switch in gevent is done through <em>yielding</em>. In this
example we have two contexts which yield to each other through invoking
<code>gevent.sleep(0)</code>.</p>
<pre><code class="python">
import gevent
def foo():
print('Running in foo')
gevent.sleep(0)
print('Explicit context switch to foo again')
def bar():
print('Explicit context to bar')
gevent.sleep(0)
print('Implicit context switch back to bar')
gevent.joinall([
gevent.spawn(foo),
gevent.spawn(bar),
])
</pre>
<p></code>
<pre><code class="python">
Running in foo
Explicit context to bar
Explicit context switch to foo again
Implicit context switch back to bar
</pre></code></p>
<p>It is illuminating to visualize the control flow of the program or walk
through it with a debugger to see the context switches as they occur.</p>
<p><img alt="Greenlet Control Flow" src="flow.gif" /></p>
<p>The real power of gevent comes when we use it for network and IO
bound functions which can be cooperatively scheduled. Gevent has
taken care of all the details to ensure that your network
libraries will implicitly yield their greenlet contexts whenever
possible. I cannot stress enough what a powerful idiom this is.
But maybe an example will illustrate.</p>
<p>In this case the <code>select()</code> function is normally a blocking
call that polls on various file descriptors.</p>
<pre><code class="python">
import time
import gevent
from gevent import select
start = time.time()
tic = lambda: 'at %1.1f seconds' % (time.time() - start)
def gr1():
# Busy waits for a second, but we don't want to stick around...
print('Started Polling: %s' % tic())
select.select([], [], [], 2)
print('Ended Polling: %s' % tic())
def gr2():
# Busy waits for a second, but we don't want to stick around...
print('Started Polling: %s' % tic())
select.select([], [], [], 2)
print('Ended Polling: %s' % tic())
def gr3():
print("Hey lets do some stuff while the greenlets poll, %s" % tic())
gevent.sleep(1)
gevent.joinall([
gevent.spawn(gr1),
gevent.spawn(gr2),
gevent.spawn(gr3),
])
</pre>
<p></code>
<pre><code class="python">
Started Polling: at 0.0 seconds
Started Polling: at 0.0 seconds
Hey lets do some stuff while the greenlets poll, at 0.0 seconds
Ended Polling: at 2.0 seconds
Ended Polling: at 2.0 seconds
</pre></code></p>
<p>Another somewhat synthetic example defines a <code>task</code> function
which is <em>non-deterministic</em>
(i.e. its output is not guaranteed to give the same result for
the same inputs). In this case the side effect of running the
function is that the task pauses its execution for a random
number of seconds.</p>
<pre><code class="python">
import gevent
import random
def task(pid):
"""
Some non-deterministic task
"""
gevent.sleep(random.randint(0,2)*0.001)
print('Task %s done' % pid)
def synchronous():
for i in xrange(10):
task(i)
def asynchronous():
threads = [gevent.spawn(task, i) for i in xrange(10)]
gevent.joinall(threads)
print('Synchronous:')
synchronous()
print('Asynchronous:')
asynchronous()
</pre>
<p></code>
<pre><code class="python">
Synchronous:
Task 0 done
Task 1 done
Task 2 done
Task 3 done
Task 4 done
Task 5 done
Task 6 done
Task 7 done
Task 8 done
Task 9 done
Asynchronous:
Task 1 done
Task 6 done
Task 0 done
Task 3 done
Task 4 done
Task 5 done
Task 7 done
Task 9 done
Task 2 done
Task 8 done
</pre></code></p>
<p>In the synchronous case all the tasks are run sequentially,
which results in the main programming <em>blocking</em> (
i.e. pausing the execution of the main program )
while each task executes.</p>
<p>The important parts of the program are the
<code>gevent.spawn</code> which wraps up the given function
inside of a Greenlet thread. The list of initialized greenlets
are stored in the array <code>threads</code> which is passed to
the <code>gevent.joinall</code> function which blocks the current
program to run all the given greenlets. The execution will step
forward only when all the greenlets terminate.</p>
<p>The important fact to notice is that the order of execution in
the async case is essentially random and that the total execution
time in the async case is much less than the sync case. In fact
the maximum time for the synchronous case to complete is when
each tasks pauses for 0.002 seconds resulting in a 0.02 seconds for the
whole queue. In the async case the maximum runtime is roughly 0.002
seconds since none of the tasks block the execution of the
others.</p>
<p>In a more common use case, asynchronously fetching data from a server,
the runtime of <code>fetch()</code> will differ between
requests, depending on the load on the remote server at the time of the request.</p>
<pre><code class="python">import gevent.monkey
gevent.monkey.patch_socket()
import gevent
import urllib2
import simplejson as json
def fetch(pid):
response = urllib2.urlopen('http://jsontime.herokuapp.com/')
result = response.read()
json_result = json.loads(result)
datetime = json_result['datetime']
print('Process %s: %s' % (pid, datetime))
return json_result['datetime']
def synchronous():
for i in range(1,10):
fetch(i)
def asynchronous():
threads = []
for i in range(1,10):
threads.append(gevent.spawn(fetch, i))
gevent.joinall(threads)
print('Synchronous:')
synchronous()
print('Asynchronous:')
asynchronous()
</code>
</pre>
<h2 id="determinism">Determinism</h2>
<p>As mentioned previously, greenlets are deterministic. Given the same
configuration of greenlets and the same set of inputs, they always
produce the same output. For example, let's spread a task across a
multiprocessing pool and compare its results to the one of a gevent pool.</p>
<pre>
<code class="python">
import time
def echo(i):
time.sleep(0.001)
return i
# Non Deterministic Process Pool
from multiprocessing.pool import Pool
p = Pool(10)
run1 = [a for a in p.imap_unordered(echo, xrange(10))]
run2 = [a for a in p.imap_unordered(echo, xrange(10))]
run3 = [a for a in p.imap_unordered(echo, xrange(10))]
run4 = [a for a in p.imap_unordered(echo, xrange(10))]
print(run1 == run2 == run3 == run4)
# Deterministic Gevent Pool
from gevent.pool import Pool
p = Pool(10)
run1 = [a for a in p.imap_unordered(echo, xrange(10))]
run2 = [a for a in p.imap_unordered(echo, xrange(10))]
run3 = [a for a in p.imap_unordered(echo, xrange(10))]
run4 = [a for a in p.imap_unordered(echo, xrange(10))]
print(run1 == run2 == run3 == run4)
</code>
</pre>
<pre>
<code class="python">False
True</code>
</pre>
<p>Even though gevent is normally deterministic, sources of
non-determinism can creep into your program when you begin to
interact with outside services such as sockets and files. Thus
even though green threads are a form of "deterministic
concurrency", they still can experience some of the same problems
that POSIX threads and processes experience.</p>
<p>The perennial problem involved with concurrency is known as a
<em>race condition</em>. Simply put, a race condition occurs when two concurrent threads
/ processes depend on some shared resource but also attempt to
modify this value. This results in resources which values become
time-dependent on the execution order. This is a problem, and in
general one should very much try to avoid race conditions since
they result in a globally non-deterministic program behavior.</p>
<p>The best approach to this is to simply avoid all global state at all
times. Global state and import-time side effects will always come
back to bite you!</p>
<h2 id="spawning-greenlets">Spawning Greenlets</h2>
<p>gevent provides a few wrappers around Greenlet initialization.
Some of the most common patterns are:</p>
<pre><code class="python">
import gevent
from gevent import Greenlet
def foo(message, n):
"""
Each thread will be passed the message, and n arguments
in its initialization.
"""
gevent.sleep(n)
print(message)
# Initialize a new Greenlet instance running the named function
# foo
thread1 = Greenlet.spawn(foo, "Hello", 1)
# Wrapper for creating and running a new Greenlet from the named
# function foo, with the passed arguments
thread2 = gevent.spawn(foo, "I live!", 2)
# Lambda expressions
thread3 = gevent.spawn(lambda x: (x+1), 2)
threads = [thread1, thread2, thread3]
# Block until all threads complete.
gevent.joinall(threads)
</pre>
<p></code>
<pre><code class="python">
Hello
I live!
</pre></code></p>
<p>In addition to using the base Greenlet class, you may also subclass
Greenlet class and override the <code>_run</code> method.</p>
<pre><code class="python">
import gevent
from gevent import Greenlet
class MyGreenlet(Greenlet):
def __init__(self, message, n):
Greenlet.__init__(self)
self.message = message
self.n = n
def _run(self):
print(self.message)
gevent.sleep(self.n)
g = MyGreenlet("Hi there!", 3)
g.start()
g.join()
</pre>
<p></code>
<pre><code class="python">
Hi there!
</pre></code></p>
<h2 id="greenlet-state">Greenlet State</h2>
<p>Like any other segment of code, Greenlets can fail in various
ways. A greenlet may fail to throw an exception, fail to halt or
consume too many system resources.</p>
<p>The internal state of a greenlet is generally a time-dependent
parameter. There are a number of flags on greenlets which let
you monitor the state of the thread:</p>
<ul>
<li><code>started</code> -- Boolean, indicates whether the Greenlet has been started</li>
<li><code>ready()</code> -- Boolean, indicates whether the Greenlet has halted</li>
<li><code>successful()</code> -- Boolean, indicates whether the Greenlet has halted and not thrown an exception</li>
<li><code>value</code> -- arbitrary, the value returned by the Greenlet</li>
<li><code>exception</code> -- exception, uncaught exception instance thrown inside the greenlet</li>
</ul>
<pre><code class="python">
import gevent
def win():
return 'You win!'
def fail():
raise Exception('You fail at failing.')
winner = gevent.spawn(win)
loser = gevent.spawn(fail)
print(winner.started) # True
print(loser.started) # True
# Exceptions raised in the Greenlet, stay inside the Greenlet.
try:
gevent.joinall([winner, loser])
except Exception as e:
print('This will never be reached')
print(winner.value) # 'You win!'
print(loser.value) # None
print(winner.ready()) # True
print(loser.ready()) # True
print(winner.successful()) # True
print(loser.successful()) # False
# The exception raised in fail, will not propagate outside the
# greenlet. A stack trace will be printed to stdout but it
# will not unwind the stack of the parent.
print(loser.exception)
# It is possible though to raise the exception again outside
# raise loser.exception
# or with
# loser.get()
</pre>
<p></code>
<pre><code class="python">
True
True
You win!
None
True
True
True
False
You fail at failing.
</pre></code></p>
<h2 id="program-shutdown">Program Shutdown</h2>
<p>Greenlets that fail to yield when the main program receives a
SIGQUIT may hold the program's execution longer than expected.
This results in so called "zombie processes" which need to be
killed from outside of the Python interpreter.</p>
<p>A common pattern is to listen SIGQUIT events on the main program
and to invoke <code>gevent.kill</code> or <code>gevent.killall</code> before exit.</p>
<pre>
<code class="python">import gevent
import signal
def run_forever():
gevent.sleep(1000)
if __name__ == '__main__':
thread = gevent.spawn(run_forever)
gevent.signal(signal.SIGQUIT, gevent.kill, thread)
thread.join()
</code>
</pre>
<h2 id="timeouts">Timeouts</h2>
<p>Timeouts are a constraint on the runtime of a block of code or a
Greenlet.</p>
<pre>
<code class="python">
import gevent
from gevent import Timeout
seconds = 10
timeout = Timeout(seconds)
timeout.start()
def wait():
gevent.sleep(10)
try:
gevent.spawn(wait).join()
except Timeout:
print('Could not complete')
</code>
</pre>
<p>They can also be used with a context manager, in a <code>with</code> statement.</p>
<pre>
<code class="python">import gevent
from gevent import Timeout
time_to_wait = 5 # seconds
class TooLong(Exception):
pass
with Timeout(time_to_wait, TooLong):
gevent.sleep(10)
</code>
</pre>
<p>In addition, gevent also provides timeout arguments for a
variety of Greenlet and data structure related calls. For example:</p>
<pre><code class="python">
import gevent
from gevent import Timeout
def wait():
gevent.sleep(2)
timer = Timeout(1).start()
thread1 = gevent.spawn(wait)
try:
thread1.join(timeout=timer)
except Timeout:
print('Thread 1 timed out')
# --
timer = Timeout.start_new(1)
thread2 = gevent.spawn(wait)
try:
thread2.get(timeout=timer)
except Timeout:
print('Thread 2 timed out')
# --
try:
gevent.with_timeout(1, wait)
except Timeout:
print('Thread 3 timed out')
</pre>
<p></code>
<pre><code class="python">
Thread 1 timed out
Thread 2 timed out
Thread 3 timed out
</pre></code></p>
<h2 id="monkeypatching">Monkeypatching</h2>
<p>Alas we come to dark corners of Gevent. I've avoided mentioning
monkey patching up until now to try and motivate the powerful
coroutine patterns, but the time has come to discuss the dark arts
of monkey-patching. If you noticed above we invoked the command
<code>monkey.patch_socket()</code>. This is a purely side-effectful command to
modify the standard library's socket library.</p>
<pre>
<code class="python">import socket
print(socket.socket)
print("After monkey patch")
from gevent import monkey
monkey.patch_socket()
print(socket.socket)
import select
print(select.select)
monkey.patch_select()
print("After monkey patch")
print(select.select)
</code>
</pre>
<pre>
<code class="python">class 'socket.socket'
After monkey patch
class 'gevent.socket.socket'
built-in function select
After monkey patch
function select at 0x1924de8
</code>
</pre>
<p>Python's runtime allows for most objects to be modified at runtime
including modules, classes, and even functions. This is generally an
astoundingly bad idea since it creates an "implicit side-effect" that is
most often extremely difficult to debug if problems occur, nevertheless
in extreme situations where a library needs to alter the fundamental
behavior of Python itself monkey patches can be used. In this case gevent
is capable of patching most of the blocking system calls in the standard
library including those in <code>socket</code>, <code>ssl</code>, <code>threading</code> and
<code>select</code> modules to instead behave cooperatively.</p>
<p>For example, the Redis python bindings normally uses regular tcp
sockets to communicate with the <code>redis-server</code> instance. Simply
by invoking <code>gevent.monkey.patch_all()</code> we can make the redis
bindings schedule requests cooperatively and work with the rest
of our gevent stack.</p>
<p>This lets us integrate libraries that would not normally work with
gevent without ever writing a single line of code. While monkey-patching
is still evil, in this case it is a "useful evil".</p>
<h1 id="data-structures">Data Structures</h1>
<h2 id="events">Events</h2>
<p>Events are a form of asynchronous communication between
Greenlets.</p>
<pre>
<code class="python">import gevent
from gevent.event import Event
'''
Illustrates the use of events
'''
evt = Event()
def setter():
'''After 3 seconds, wake all threads waiting on the value of evt'''
print('A: Hey wait for me, I have to do something')
gevent.sleep(3)
print("Ok, I'm done")
evt.set()
def waiter():
'''After 3 seconds the get call will unblock'''
print("I'll wait for you")
evt.wait() # blocking
print("It's about time")
def main():
gevent.joinall([
gevent.spawn(setter),
gevent.spawn(waiter),
gevent.spawn(waiter),
gevent.spawn(waiter),
gevent.spawn(waiter),
gevent.spawn(waiter)
])
if __name__ == '__main__': main()
</code>
</pre>
<p>An extension of the Event object is the AsyncResult which
allows you to send a value along with the wakeup call. This is
sometimes called a future or a deferred, since it holds a
reference to a future value that can be set on an arbitrary time
schedule.</p>
<pre>
<code class="python">import gevent
from gevent.event import AsyncResult
a = AsyncResult()
def setter():
"""
After 3 seconds set the result of a.
"""
gevent.sleep(3)
a.set('Hello!')
def waiter():
"""
After 3 seconds the get call will unblock after the setter
puts a value into the AsyncResult.
"""
print(a.get())
gevent.joinall([
gevent.spawn(setter),
gevent.spawn(waiter),
])
</code>
</pre>
<h2 id="queues">Queues</h2>
<p>Queues are ordered sets of data that have the usual <code>put</code> / <code>get</code>
operations but are written in a way such that they can be safely
manipulated across Greenlets.</p>
<p>For example if one Greenlet grabs an item off of the queue, the
same item will not be grabbed by another Greenlet executing
simultaneously.</p>
<pre><code class="python">
import gevent
from gevent.queue import Queue
tasks = Queue()
def worker(n):
while not tasks.empty():
task = tasks.get()
print('Worker %s got task %s' % (n, task))
gevent.sleep(0)
print('Quitting time!')
def boss():
for i in xrange(1,25):
tasks.put_nowait(i)
gevent.spawn(boss).join()
gevent.joinall([
gevent.spawn(worker, 'steve'),
gevent.spawn(worker, 'john'),
gevent.spawn(worker, 'nancy'),
])
</pre>
<p></code>
<pre><code class="python">
Worker steve got task 1
Worker john got task 2
Worker nancy got task 3
Worker steve got task 4
Worker john got task 5
Worker nancy got task 6
Worker steve got task 7
Worker john got task 8
Worker nancy got task 9
Worker steve got task 10
Worker john got task 11
Worker nancy got task 12
Worker steve got task 13
Worker john got task 14
Worker nancy got task 15
Worker steve got task 16
Worker john got task 17
Worker nancy got task 18
Worker steve got task 19
Worker john got task 20
Worker nancy got task 21
Worker steve got task 22
Worker john got task 23
Worker nancy got task 24
Quitting time!
Quitting time!
Quitting time!
</pre></code></p>
<p>Queues can also block on either <code>put</code> or <code>get</code> as the need arises.</p>
<p>Each of the <code>put</code> and <code>get</code> operations has a non-blocking
counterpart, <code>put_nowait</code> and
<code>get_nowait</code> which will not block, but instead raise
either <code>gevent.queue.Empty</code> or
<code>gevent.queue.Full</code> if the operation is not possible.</p>
<p>In this example we have the boss running simultaneously to the
workers and have a restriction on the Queue preventing it from containing
more than three elements. This restriction means that the <code>put</code>
operation will block until there is space on the queue.
Conversely the <code>get</code> operation will block if there are
no elements on the queue to fetch, it also takes a timeout
argument to allow for the queue to exit with the exception
<code>gevent.queue.Empty</code> if no work can be found within the
time frame of the Timeout.</p>
<pre><code class="python">
import gevent
from gevent.queue import Queue, Empty
tasks = Queue(maxsize=3)
def worker(name):
try:
while True:
task = tasks.get(timeout=1) # decrements queue size by 1
print('Worker %s got task %s' % (name, task))
gevent.sleep(0)
except Empty:
print('Quitting time!')
def boss():
"""
Boss will wait to hand out work until an individual worker is
free since the maxsize of the task queue is 3.
"""
for i in xrange(1,10):
print('Assigned work %s in iteration 1' % (i))
tasks.put(i)
print('Assigned all work in iteration 1')
for i in xrange(10,20):
print('Assigned work %s in iteration 2' % (i))
tasks.put(i)
print('Assigned all work in iteration 2')
gevent.joinall([
gevent.spawn(boss),
gevent.spawn(worker, 'steve'),
gevent.spawn(worker, 'john'),
gevent.spawn(worker, 'bob'),
])
</pre>
<p></code>
<pre><code class="python">
Assigned work 1 in iteration 1
Assigned work 2 in iteration 1
Assigned work 3 in iteration 1
Assigned work 4 in iteration 1
Worker steve got task 1
Worker john got task 2
Worker bob got task 3
Assigned work 5 in iteration 1
Assigned work 6 in iteration 1
Assigned work 7 in iteration 1
Worker steve got task 4
Worker john got task 5
Worker bob got task 6
Assigned work 8 in iteration 1
Assigned work 9 in iteration 1
Assigned all work in iteration 1
Assigned work 10 in iteration 2
Worker steve got task 7
Worker john got task 8
Worker bob got task 9
Assigned work 11 in iteration 2
Assigned work 12 in iteration 2
Assigned work 13 in iteration 2
Worker steve got task 10
Worker john got task 11
Worker bob got task 12
Assigned work 14 in iteration 2
Assigned work 15 in iteration 2
Assigned work 16 in iteration 2
Worker steve got task 13
Worker john got task 14
Worker bob got task 15
Assigned work 17 in iteration 2
Assigned work 18 in iteration 2
Assigned work 19 in iteration 2
Worker steve got task 16
Worker john got task 17
Worker bob got task 18
Assigned all work in iteration 2
Worker steve got task 19
Quitting time!
Quitting time!
Quitting time!
</pre></code></p>
<h2 id="groups-and-pools">Groups and Pools</h2>
<p>A group is a collection of running greenlets which are managed
and scheduled together as group. It also doubles as parallel
dispatcher that mirrors the Python <code>multiprocessing</code> library.</p>
<pre><code class="python">
import gevent
from gevent.pool import Group
def talk(msg):
for i in xrange(3):
print(msg)
g1 = gevent.spawn(talk, 'bar')
g2 = gevent.spawn(talk, 'foo')
g3 = gevent.spawn(talk, 'fizz')
group = Group()
group.add(g1)
group.add(g2)
group.join()
group.add(g3)
group.join()
</pre>
<p></code>
<pre><code class="python">
bar
bar
bar
foo
foo
foo
fizz
fizz
fizz
</pre></code></p>
<p>This is very useful for managing groups of asynchronous tasks.</p>
<p>As mentioned above, <code>Group</code> also provides an API for dispatching
jobs to grouped greenlets and collecting their results in various
ways.</p>
<pre><code class="python">
import gevent
from gevent import getcurrent
from gevent.pool import Group
group = Group()
def hello_from(n):
print('Size of group %s' % len(group))
print('Hello from Greenlet %s' % id(getcurrent()))
group.map(hello_from, xrange(3))
def intensive(n):
gevent.sleep(3 - n)
return 'task', n
print('Ordered')
ogroup = Group()
for i in ogroup.imap(intensive, xrange(3)):
print(i)
print('Unordered')
igroup = Group()
for i in igroup.imap_unordered(intensive, xrange(3)):
print(i)
</pre>
<p></code>
<pre><code class="python">
Size of group 3
Hello from Greenlet 4405439216