forked from sdiehl/gevent-tutorial
/
index.html
1625 lines (1366 loc) · 49.9 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 チュートリアル</title>
</head>
<body>
<div class="container">
<div id="sidebar" class="three columns sidebar">
<nav>
</nav>
</div>
<div class="twelve columns offset-by-three content">
<header>
<h1>Python プログラマーのための <span class="green">gevent</span> チュートリアル</h1>
<h3 class="author">
Written by the Gevent Community
</h3>
<blockquote>
gevent は <a href="http://software.schmorp.de/pkg/libev.html">libev</a> を元にした並行ライブラリです。
ネットワークや並行プログラミングのためのクリーンなAPIを提供しています。
</blockquote>
</header>
<div class="toc">
<ul>
<li><a href="#">はじめに</a><ul>
<li><a href="#_1">寄稿者</a><ul>
<li><a href="#_2">日本語訳について</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#_3">コア</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="#_4">モンキーパッチ</a></li>
</ul>
</li>
<li><a href="#_5">データ構造</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="">はじめに</h1>
<p>このチュートリアルはある程度の Python の知識を前提としていますが、
それ以上の知識は前提としていません。
並列プログラミングの知識も必要ありません。
このチュートリアルの目的は、 gevent を扱う道具を提供し、
読者がすでに持っている一般的な並列プログラミングの問題を手なづけて
非同期プログラムを書き始められるように手助けすることです。</p>
<h3 id="_1">寄稿者</h3>
<p>時系列順の寄稿者:
<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></p>
<p>そして Denis Bilenko に、 gevent の開発とこのチュートリアルを作る上での
指導について感謝します。</p>
<p>この共同作業によるドキュメントは MIT ライセンスにて公開されています。
何か追記したいことがあったり、タイプミスを発見した場合は、
<a href="https://github.com/sdiehl/gevent-tutorial">Github</a> で fork して pull
request を送ってください。その他のどんな貢献も歓迎します。</p>
<h3 id="_2">日本語訳について</h3>
<p>時系列順の翻訳者:
<a href="http://github.com/methane">methane</a></p>
<p>翻訳は <a href="http://github.com/methane/gevent-tutorial-ja">gevent-tutorial-ja</a>
で行なっています。
翻訳に対する修正依頼等はこちらにお願いします.</p>
<h1 id="_3">コア</h1>
<h2 id="greenlets">Greenlets</h2>
<p>gevent で使われている一番重要なパターンが <strong>Greenlet</strong> という
Python のC拡張の形で提供された軽量なコルーチンです。
すべての Greenlet はメインプログラムのOSプロセス内で実行されますが、
協調的にスケジューリングされます.</p>
<blockquote>
<p>Only one greenlet is ever running at any given time.
(どの時点をとっても常にひとつの greenlet だけが動いている)</p>
</blockquote>
<p>これは、 <code>multiprocessing</code> や <code>threading</code> が提供している、
OS がスケジューリングして本当に並列に動くプロセスや POSIX スレッドを利用した
並列機構とは異なるものです。</p>
<h2 id="synchronous-asynchronous-execution">Synchronous & Asynchronous Execution</h2>
<p>並行プログラムのコアとなる考え方は、大きいタスクは小さいサブタスクに分割して、
それらを1つずつ、あるいは <em>同期的に</em> 動かす代わりに、同時に、あるいは
<em>非同期に</em> 動かすことです。
2つのサブタスク間の切り替えは <em>コンテキストスイッチ</em> と呼ばれます。</p>
<p>gevent のコンテキストスイッチは <em>譲渡(yield)</em> によって行われます。
次の例では、2つのコンテキストが <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>次の制御フローを視覚化した画像を見るか、このサンプルプログラムを
デバッガーでステップ実行してコンテキストスイッチが起こる様子を確認してください。</p>
<p><img alt="Greenlet Control Flow" src="flow.gif" /></p>
<p>gevent が本当の力を発揮するのは、ネットワークやIOバウンドの、協調的に
スケジュールできる関数を実行するために利用する場合です。
gevent はすべての詳細部分の面倒を見て、可能な限りネットワークライブラリが
暗黙的に greenlet コンテキストを譲渡するようにします。
私はこれがどれだけ強力な方法なのかをうまく強調することができません。
でも、次の例が示してくれると思います。</p>
<p>この例では、 <code>select()</code> 関数は通常ブロックする関数で、複数の
ファイルディスクリプタをポーリングします。</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: ', tic())
select.select([], [], [], 2)
print('Ended Polling: ', tic())
def gr2():
# Busy waits for a second, but we don't want to stick around...
print('Started Polling: ', tic())
select.select([], [], [], 2)
print('Ended Polling: ', tic())
def gr3():
print("Hey lets do some stuff while the greenlets poll, at", 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 at 0.0 seconds
Ended Polling: at 2.0 seconds
Ended Polling: at 2.0 seconds
</pre></code></p>
<p>もう一つのすこし人工的な例として、 <em>非決定論的な</em> (同じ入力に対して
出力が同じになるとは限らない) <code>task</code> 関数を定義しています。
この例では、 <code>task</code> 関数を実行すると副作用としてランダムな秒数だけ
タスクの実行を停止します。</p>
<pre><code class="python">
import gevent
import random
def task(pid):
"""
Some non-deterministic task
"""
gevent.sleep(random.randint(0,2))
print('Task', pid, 'done')
def synchronous():
for i in range(1,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 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 2 done
Task 5 done
Task 6 done
Task 7 done
Task 9 done
Task 4 done
Task 3 done
Task 0 done
Task 8 done
Task 1 done
</pre></code></p>
<p>同期的に実行した場合、全てのタスクはシーケンシャルに実行され、
メインプログラムは各タスクを実行している間 <em>ブロックする</em>
(メインプログラムの実行が停止される) ことになります。</p>
<p>このプログラムの重要な部分は、与えられた関数を greenlet スレッドの中に
ラップする <code>gevent.spawn</code> です。
生成された greenlet のリストが <code>threads</code> 配列に格納され、
<code>gevent.joinall</code> 関数に渡されます。この関数は今のプログラムを、与えられた
すべての greenlet を実行するためにブロックします。
すべての greenlet が終了した時に次のステップが実行されます。</p>
<p>注意すべき重要な点として、非同期に実行した場合の実行順序は本質的に
ランダムであり、トータルの実行時間は同期的に実行した場合よりもずっと
短くなります。実際、各タスクが2秒ずつ停止すると、同期的に実行した場合は
すべてのタスクを実行するのに20秒かかりますが、非同期に実行した場合は
各タスクが他のタスクの実行を止めないのでだいたい2秒で終了します。</p>
<p>もっと一般的なユースケースとして、サーバーからデータを非同期に取得する場合、
<code>fetch()</code> の実行時間はリモートサーバーの負荷などによってリクエストごとに
異なります。</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://json-time.appspot.com/time.json')
result = response.read()
json_result = json.loads(result)
datetime = json_result['datetime']
print 'Process ', 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>先に触れたように、 greenlet は決定論的に動作します。
同じように設定した greenlets があって、同じ入力が与えられた場合、
必ず同じ結果になります。例として、タスクを multiprocessing の pool に
与えた場合と 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>gevent が通常決定論的だといっても、ソケットやファイルなどの外部の
サービスとのやりとりを始めると非決定論的な入力がプログラムに入り込んできます。
green スレッドが "決定論的な並行" であっても、 POSIX スレッドやプロセスを
使った場合に起きる問題の一部が起こります。</p>
<p>並行プログラミングにずっと付きまとう問題が
<em>レースコンディション(race condition)</em> です。
簡単に言うと、2つの並行するスレッドやプロセスが幾つかの共有リソース
(訳注:グローバル変数など)に依存しており、しかもそれを変更しようとする問題です。
結果としてそのリソースの状態は実行順序に依存してしまいます。
一般的にプログラマーはこの問題を可能な限り避けようとするべきです。
そうしないとプログラムのふるまいが全体として非決定性になってしまうからです。</p>
<p>レースコンディションを避ける一番の方法は、常に、全てのグローバルな状態を避ける事です。
グローバルな状態や import 時の副作用はいつでもあなたに噛みついてきます。
(訳注: import 時の副作用は、 import 順序によってプログラムの動作を変えてしまう、
Python でプログラミングをすると忘れた頃にハマる問題のタネです. 並行プログラミングとは
無関係です)</p>
<h2 id="spawning-greenlets">Spawning Greenlets</h2>
<p>gevent は greenlet の初期化のラッパーを幾つか提供しています。
幾つかのよくあるパターンは:</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 runing 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>Greenlet クラスを直接使うだけでなく、 Greenlet のサブクラスを作って
<code>_run</code> メソッドをオーバーライドすることもできます。</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>他のどんなコードでもあるように、 greenlet もいろいろな失敗をすることがあります。
greenlet は例外を投げそこねるかもしれませんし、停止できなくなったり、
システムリソースを食い過ぎるかもしれません。</p>
<p>greenlet の内部状態は基本的に時間とともに変化するパラメーターになります。
greenlet の状態をモニターするための幾つかのフラグがあります。</p>
<ul>
<li><code>started</code> -- bool値: greenlet が開始しているかどうか.</li>
<li><code>ready()</code> -- bool値, greenlet が停止(halt)しているかどうか.</li>
<li><code>successful()</code> -- bool値, greenlet が例外を投げずに終了したかどうか.</li>
<li><code>value</code> -- 任意の値, greenlet が返した値.</li>
<li><code>exception</code> -- 例外, 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 propogate 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>メインプログラムが SIGQUIT を受信した時に yield しない greenlet
がプログラムを実行させ続ける可能性があります。
この状態は "ゾンビプロセス" と呼ばれ、 Python インタープリターの
外から kill してやる必要があります。</p>
<p>一般的なパターンはメインプログラムが SIGQUIT イベントを受信して、
exit する前に <code>gevent.shutdown</code> を呼び出すことです。</p>
<pre>
<code class="python">import gevent
import signal
def run_forever():
gevent.sleep(1000)
if __name__ == '__main__':
gevent.signal(signal.SIGQUIT, gevent.shutdown)
thread = gevent.spawn(run_forever)
thread.join()
</code>
</pre>
<h2 id="timeouts">Timeouts</h2>
<p>タイムアウトとは、コードブロックや 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>もしくはコンテキストマネージャーとして <code>with</code> 文を使います。</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>加えて、 gevent は多くの greenlet やデータ構造に関する関数に timeout
引数を提供しています。例えば:</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="_4">モンキーパッチ</h2>
<p>Gevent の暗黒面に触れていきます。
強力なコルーチンのパターンを推奨するためにここまでモンキーパッチに
ついて触れるのを避けて来ましたが、そろそろこの黒魔術について話す時です。
いままでのコードに <code>monkey.patch_socket()</code> というコマンドが出てきたのに
気づきましたか?これは標準ライブラリの socket ライブラリを改変するコマンドです。</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 のランタイムは、モジュール、クラス、そして関数に至るまで、
ほとんどのオブジェクトについて実行時に編集することを許しています。
これは一般的にはとーっても悪いやり方です。「暗黙の副作用」を作り出し、
問題が発生した時にデバッグするのを非常に難しくするからです。
それでも、 Python 自体の基本的な振る舞いを変更する必要がある例外的な状況では
モンキーパッチを使うことができます。
この場合、 gevent は標準ライブラリの <code>socket, ssl, threading, select</code> などにあるの多くの
ブロックするシステムコールを協調的に動作するようにパッチします。</p>
<p>例えば、 Redis の Python バインディングは通常の TCP ソケットを使って
<code>redis-server</code> インスタンスと通信します。
<code>gevent.monkey.patch_all()</code> を実行するだけで、 redis バインディングは
協調的にリクエストをするようになり、その他の gevent のスタックと一緒に
動くようになります。</p>
<p>モンキーパッチを使えば、そのままでは gevent で動作しないライブラリを
1行のコードを書くだけで統合できるようになります。
モンキーパッチは邪悪ですが、この場合は必要悪です。</p>
<h1 id="_5">データ構造</h1>
<h2 id="events">Events</h2>
<p>イベントは greenlet 間の非同期通信の一つです。</p>
<pre>
<code class="python">import gevent
from gevent.event import AsyncResult
a = AsyncResult()
def setter():
"""
After 3 seconds set wake all threads waiting on the value of
a.
"""
gevent.sleep(3)
a.set()
def waiter():
"""
After 3 seconds the get call will unblock.
"""
a.get() # blocking
print 'I live!'
gevent.joinall([
gevent.spawn(setter),
gevent.spawn(waiter),
])
</code>
</pre>
<p>Event オブジェクトの拡張の AsyncResult を使うと、モーニングコール
(wakeup call) 付きの値を送ることができます。
これは将来どこかのタイミングで設定される値に対する参照を持っているので、
future とか deferred と呼ばれることもあります。</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>キューはデータの順序付き集合で、標準的な <code>put / get</code> 操作を持っています。
これは greenlet をまたいで安全に操作できるように実装されています。</p>
<p>例えば、ある greenlet がキューから要素を取得した時、同じ要素が並行して
動いている他の greenlet でも取得されることはありません。</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 nancy got task 5
Worker john got task 6
Worker steve got task 7
Worker john got task 8
Worker nancy got task 9
Worker steve got task 10
Worker nancy got task 11
Worker john got task 12
Worker steve got task 13
Worker john got task 14
Worker nancy got task 15
Worker steve got task 16
Worker nancy got task 17
Worker john got task 18
Worker steve got task 19
Worker john got task 20
Worker nancy got task 21
Worker steve got task 22
Worker nancy got task 23
Worker john got task 24
Quitting time!
Quitting time!
Quitting time!
</pre></code></p>
<p>キューは必要があれば <code>put</code> でも <code>get</code> でもブロックすることがあります。</p>
<p><code>put</code> と <code>get</code> にはそれぞれブロックしないバージョンとして
それぞれ <code>put_nowait</code> と <code>get_nowait</code> が用意されています。
これらの操作は実行できない場合はブロックする代わりに
<code>gevent.queue.Empty</code> か <code>gevent.queue.Full</code> 例外を発生させます。</p>
<p>次の例では、並行して動いている boss と複数の worker がいて、
3要素以上格納できない制限付きのキューがあります。
この制限により、キューに空きが無いときは空きができるまで <code>put</code>
操作がブロックして、キューが空の場合は要素が格納されるまで <code>get</code>
操作がブロックします。
<code>get</code> には timeout 引数を設定して、その時間内に要素を取得できない
場合は <code>gevent.queue.Empty</code> 例外を発生させて終了します。</p>
<pre><code class="python">
import gevent
from gevent.queue import Queue, Empty
tasks = Queue(maxsize=3)
def worker(n):
try:
while True:
task = tasks.get(timeout=1) # decrements queue size by 1
print('Worker %s got task %s' % (n, task))
gevent.sleep(0)
except Empty:
print('Quitting time!')
def boss():
"""
Boss will wait to hand out work until a individual worker is
free since the maxsize of the task queue is 3.
"""
for i in xrange(1,10):
tasks.put(i)
print('Assigned all work in iteration 1')
for i in xrange(10,20):
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">
Worker steve got task 1
Worker john got task 2
Worker bob got task 3
Worker steve got task 4
Worker bob got task 5
Worker john got task 6
Assigned all work in iteration 1
Worker steve got task 7
Worker john got task 8
Worker bob got task 9
Worker steve got task 10
Worker bob got task 11
Worker john got task 12
Worker steve got task 13
Worker john got task 14
Worker bob got task 15
Worker steve got task 16
Worker bob got task 17
Worker john 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>グループとは、複数の greenlet をまとめてスケジュールしたり管理するものです。
Python の <code>multiprocessing</code> ライブラリの並列ディスパッチを置き換える用途にも使えます。</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>これは非同期なタスクのグループを管理するのに便利です。</p>
<p>上で述べたように、 Group はグループ化された greenlet に対してジョブを
ディスパッチし、その結果をいろいろな方法で取得するためのAPIを提供しています。</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', 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 4433885296
Size of group 3
Hello from Greenlet 4434739440
Size of group 3
Hello from Greenlet 4434739920
Ordered
('task', 0)
('task', 1)
('task', 2)
Unordered
('task', 2)
('task', 1)
('task', 0)
</pre></code></p>
<p>pool は並行数を制限しながら動的な数の greenlet を扱うためのものです。
たくさんのネットワークやIOバウンドのタスクを並列に実行したい場合に
最適です。</p>
<pre><code class="python">
import gevent
from gevent.pool import Pool
pool = Pool(2)
def hello_from(n):
print('Size of pool', len(pool))
pool.map(hello_from, xrange(3))
</pre>
<p></code>
<pre><code class="python">
Size of pool 2
Size of pool 2
Size of pool 1
</pre></code></p>
<p>gevent を使ったサービスを作るときに、よく中央に pool を持った
構成で設計します。
例えばたくさんのソケットをポーリングするクラスです。</p>
<pre>
<code class="python">from gevent.pool import Pool
class SocketPool(object):
def __init__(self):
self.pool = Pool(1000)
self.pool.start()
def listen(self, socket):
while True:
socket.recv()
def add_handler(self, socket):
if self.pool.full():
raise Exception("At maximum pool size")
else:
self.pool.spawn(self.listen, socket)
def shutdown(self):
self.pool.kill()
</code>
</pre>
<h2 id="locks-and-semaphores">Locks and Semaphores</h2>
<p>セマフォ(Semaphore) は greenlet に並行アクセスや並行実行を調整する低レベルな
同期機構です。