forked from sdiehl/gevent-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.html
More file actions
1518 lines (1249 loc) · 49.7 KB
/
index.html
File metadata and controls
1518 lines (1249 loc) · 49.7 KB
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>
<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>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>기반의 동시성 라이브러리 입니다. gevent는 동시성과 네트워크 관련 작업들을 위한 다양한 API를 제공합니다.
</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>이 튜토리얼은 중급 레벨의 파이썬 지식을 필요로 합니다. 동시성에 대한 선수 지식은 필요하지 않습니다. 이 튜토리얼의 목적은 독자에게 gevent를 사용하기 위한 도구들을 소개하고, 독자가 가지고 있었던 동시성 문제를 해결하고 비동기 어플리케이션을 작성하는 것을 돕는 것 입니다.</p>
<h3 id="contributors">Contributors</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>
<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>gevent 튜토리얼을 쓰는데 도움을 주신 Denis Bilenko에게 감사의 뜻을 전합니다.</p>
<p>이 문서는 MIT license로 공개된 협업 문서입니다. 추가할 내용이나 오타를 발견하신 경우 <a href="https://github.com/sdiehl/gevent-tutorial">Github</a>로 pull request를 보내주세요. </p>
<p>한글 번역 오타 및 오역 수정은 <a href="https://github.com/leekchan/gevent-tutorial-ko">한글 번역 repository</a>에 issue 생성 또는 pull request 부탁드립니다.</p>
<p>이 페이지는
<a href="http://methane.github.com/gevent-tutorial-ja">일본어</a>,
<a href="http://xlambda.com/gevent-tutorial/">중국어</a>,
<a href="http://ovnicraft.github.io/gevent/">스페인어</a>,
<a href="http://pbertera.github.io/gevent-tutorial-it/">이탈리아어</a>, 그리고
<a href="https://hellerve.github.io/gevent-tutorial-de">독일어</a>로도 번역되어 있습니다.</p>
<h1 id="core">Core</h1>
<h2 id="greenlets">Greenlets</h2>
<p>gevent에서 사용되는 주된 패턴은 <strong>Greenlet</strong>입니다. Greenlet은 C 확장 모듈 형태로 제공되는 경량 코루틴 입니다. Greenlet들은 메인 프로그램을 실행하는 OS process 안에서 모두 실행되지만 상호작용하며 스케줄링됩니다.</p>
<blockquote>
<p>한 번에 오직 하나의 greenlet만이 실행됩니다.</p>
</blockquote>
<p>운영체제에 의해 스케줄링되는 process들과 POSIX 쓰레드들을 사용하여 실제로 병렬로 실행되는 <code>multiprocessing</code> 나 <code>threading</code>을 이용한 병렬처리들과는 다릅니다.</p>
<h2 id="synchronous-asynchronous-execution">Synchronous & Asynchronous Execution</h2>
<p>동시성 처리의 핵심 개념은 큰 단위의 task를 한번에 <em>동기로</em> 처리하는 대신, 작은 단위의 subtask들로 쪼개서 동시에 <em>비동기</em>로 실행시키는 것입니다. 두 subtask간의 스위칭을 <em>컨텍스트 스위칭</em>이라고 합니다. </p>
<p>gevent에서는 컨텍스트 스위칭을 <em>yielding</em>을 이용해서 합니다. 아래 코드는 <code>gevent.sleep(0)</code>를 사용해 두 컨텍스트 사이에서 yield를 하는 예제입니다.</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 bound 함수들을 작성할때 발휘됩니다. gevent는 네트워크 라이브러리들이 암시적으로 greenlet 컨텍스트들이 가능한 시점에 암시적으로 yield 하도록 보장합니다. 이 개념은 정말 강조하고 싶은 중요한 개념인데, 예제를 통해서 살펴보도록 하겠습니다.</p>
<p>아래 코드는 <code>select()</code> 함수가 일반적인 blocking call을 하는 예시입니다.</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>아래 코드는 <em>non-deterministic</em>(i.e. 같은 입력에 대해 같은 결과를 보장하지 않음)한 <code>task</code> 함수를 정의하는 또 다른 인위적인 예제입니다. 이 함수 실행의 부작용은 task가 무작위 시간 동안 실행되고 일시중지되는 것입니다.</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 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 1 done
Task 4 done
Task 6 done
Task 9 done
Task 0 done
Task 2 done
Task 3 done
Task 7 done
Task 8 done
Task 5 done
</pre></code></p>
<p>동기(synchronous)처리시 모든 task들이 순차적으로 실행되고, 다른 task들이 각각 동작하는 동안 <em>blocking</em>(i.e. 프로그램의 동작을 일시중지함.)방식으로 동작합니다. </p>
<p>이 프로그램에서 중요한 부분은 greentlet 쓰레드 안에서 주어진 함수를 감싸고 있는 <code>gevent.spawn</code>입니다. 초기화된 greenlet들은 <code>threads</code> 배열안에 담겨서 <code>gevent.joinall</code>로 넘겨집니다. 이때, <code>gevent.joinall</code>은 모든 넘겨진 greenlet들이 실행될때 까지 block되어 있습니다. 이 greenlet들이 완전히 종료되고 나면 다음 코드가 실행됩니다.</p>
<p>주목해야 할 중요한 사실은 비동기(asynchronous)처리 시 실행 순서가 보장되지 않고 실행시간이 동기(synchronous)처리 시보다 훨씬 줄어든다는 점입니다. 실제로 동기(synchronous)처리 예제를 완료하는 데 걸리는 최대 시간은 각 task가 0.002초 동안 일시중지 될 때 모두 실행되는데 0.02초입니다. 비동기(asynchronous)처리 예제에서는 task들이 서로 실행을 block 하지 않으므로 최대 실행 시간이 약 0.002초입니다.</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 %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>이전에 언급한 것처럼, greenlet은 deterministic 합니다. 같은 greenlet 세팅과 같은 입력이 주어졌을때, 언제나 같은 결과를 출력합니다. 예시로, task를 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가 일반적으로 deterministic 하다고 해도, 소켓과 파일과 같은 외부 서비스와 연동할 때 non-deterministic한 입력들이 들어올 수 있습니다. 그러므로 green 쓰레드가 "deterministic
concurrency" 형태라고 해도, POSIX 쓰레드들과 프로세스들을 다룰 때 만나는 문제들을 경험할 수 있습니다.</p>
<p>동시성을 다룰 때 만날 수 있는 문제로 <em>race condition</em>이 있습니다. 간단히 요약하자면, race condition은 두 개의 동시에 실행되는 쓰레드나 프로세스들이 같은 공유 자원을 수정하려고 할 때 발생합니다. 이때 해당 공유자원의 결과 값은 실행 순서에 따라 달라지게 됩니다. 이런 결과는 non-deterministic한 프로그램 동작을 야기하기 때문에 발생시키지 않기 위해 노력해야 합니다. </p>
<p>가장 좋은 접근법은 공유 자원을 사용하지 않는 것입니다. 공유자원을 잘못 사용하면 부작용이 엄청나니 주의해야 합니다!</p>
<h2 id="spawning-greenlets">Spawning Greenlets</h2>
<p>gevent는 greenlet 초기화를 위한 몇 가지 wrapper들을 제공합니다.
일반적인 패턴은 다음과 같습니다:</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>Greenlet 클래스를 사용하는것 외에도, Greenlet 클래스를 상속하고 <code>_run</code> 함수를 override 하는 방법도 있습니다.</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의 내부 상태는 대체로 time-dependent합니다. greenlet에는 쓰레드의 상태를 모니터링 할 수 있는 다양한 flag들이 있습니다:</p>
<ul>
<li><code>started</code> -- Boolean, Greenlet이 실행되었는지 여부를 나타냅니다</li>
<li><code>ready()</code> -- Boolean, Greenlet이 정지되었는지 여부를 나타냅니다</li>
<li><code>successful()</code> -- Boolean, Greenlet이 예외를 발생시키지 않고 정지되었는지 여부를 나타냅니다.</li>
<li><code>value</code> -- 어떠한 타입도 가능, Greenlet에 의해서 리턴된 값입니다.</li>
<li><code>exception</code> -- exception, 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>메인 프로그램이 SIGQUIT 시그널을 받은 시점에 yield를 실패한 Greenlet은 예상보다 오래 실행이 정지되어 있을 수 있습니다. 이런 프로세스는 "좀비 프로세스"라고 불리고, 파이썬 인터프리터 외부에서 kill되어야 합니다.</p>
<p>일반적인 패턴은 메인 프로그램에서 SIGQUIT 시그널에 대기하고 있다가 프로그램이 종료되기 전에 <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.kill)
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> 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>또한, gevent는 Greenlet 호출과 관련된 타임아웃 파라미터들을 제공합니다. 예를 들면 다음과 같습니다:</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>유감스럽게도 gevent의 어두운 면을 보게 되었습니다. 지금까지 강력한 코루틴 패턴들을 사용해보기 위해 monkey patching에 대해 언급하지 않았었는데요, monkey patching의 어두운 면에 대해 언급할 때가 되었습니다. 위에서 <code>monkey.patch_socket()</code>를 사용했던 것을 눈치채셨는지 모르겠는데요, 이 명령은 파이썬 기본 소켓 라이브러리를 수정하여 부작용을 유발할 수 있는 명령입니다.</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>파이썬은 런타임에 모듈, 클래스, 심지어 함수까지도 수정하는 것을 허용합니다. 이는 문제가 발생했을 때 디버깅을 매우 어렵게 만드는 "암시적인 부작용"을 유발할 수 있는 안 좋은 생각입니다. 그럼에도 불구하고, monkey patching은 라이브러리가 파이썬의 기본 동작을 변경해야 하는 극단적인 상황에서 사용될 수 있습니다. monkey patching덕분에 gevent는 <code>socket</code>, <code>ssl</code>, <code>threading</code>, 그리고 <code>select</code> 과 같은 기본 라이브러리들에 있는 blocking system call들이 동시에 실행될 수 있도록 수정할 수 있습니다.</p>
<p>예를 들어, Redis 파이썬 바인딩은 Redis 서버와 통신하기 위해 기본 tcp 소켓을 합니다. <code>gevent.monkey.patch_all()</code>를 실행시키는 것 만으로 Redis 바인딩이 요청들을 동시에 실행될 수 있도록 스케쥴링 되도록 만들고 gevent 코드에서 동작하도록 만들 수 있습니다.</p>
<p>이는 별도의 코드 작성 없이도 라이브러리들을 연동하는 것을 가능하게 합니다. monkey patching은 여전히 악이지만, 이 경우에는 "필요악"입니다.</p>
<h1 id="data-structures">Data Structures</h1>
<h2 id="events">Events</h2>
<p>Event는 Greenlet 간의 비동기 통신에 사용됩니다.</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>Event 객체의 확장은 wakeup call과 함께 값을 전송할 수 있는 AsyncResult입니다. AsyncResult는 임의의 시간에 할당될 미래 값에 대한 레퍼런스를 갖고 있기 때문에, 때때로 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>Queue는 일반적인 <code>put</code> 과 <code>get</code> 연산을 지원하지만 Greenlet 사이에서 안전하게 조작되는 것이 보장되는 순서를 가진 데이터들의 집합입니다.</p>
<p>예를 들어 한 Greenlet이 queue에서 값 하나를 가져왔을 때, 해당 값이 다른 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 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>또한 Queue는 <code>put</code>이나 <code>get</code> 연산 시 block 됩니다. </p>
<p>non-blocking 연산이 필요할 때는 block이 되지 않는 <code>put_nowait</code>과 <code>get_nowait</code>을 사용할 수 있습니다. 대신 연산이 불가능할 때는 <code>gevent.queue.Empty</code> 나 <code>gevent.queue.Full</code> 예외를 발생시킵니다.</p>
<p>아래 코드는 상사가 3명의 작업자(steve, john, nancy)에게 동시에 일을 시키는데 Queue가 3개 이상의 요소를 담지 않도록 제한하는 예시입니다. 이 제한은 <code>put</code>연산이 Queue에 남은 공간이 있을 때 까지 block 되어야 함을 의미합니다. 반대로 <code>get</code> 연산은 Queue에 요소가 없으면 block 되는데, 일정 시간이 지날 때 까지 요소가 들어오지 않으면 <code>gevent.queue.Empty</code> 예외를 발생시키면서 종료될 수 있도록 타임아웃 파라미터를 설정할 수 있습니다.</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 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 john got task 5
Worker bob 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 john got task 11
Worker bob got task 12
Worker steve got task 13
Worker john got task 14
Worker bob got task 15
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>Group은 동시에 관리되고 스케쥴링 되는 실행 중인 Greenlet들의 집합입니다. </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>Group은 비동기 task 집합들을 관리하는 데 굉장히 유용합니다.</p>
<p><code>Group</code>은 작업들을 Greenlet집합에서 실행시키고 결과들을 다양한 방법을 통해 수집할 수 있습니다.</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 4464465552
Size of group 3
Hello from Greenlet 4464465232
Size of group 3
Hello from Greenlet 4464467472
Ordered
('task', 0)
('task', 1)
('task', 2)
Unordered
('task', 2)
('task', 1)
('task', 0)
</pre></code></p>
<p>Pool은 동시에 제한된 개수의 Greenlet을 실행시킬 수 있도록 해줍니다. Pool은 대량의 네트워크 또는 IO bound 작업들을 동시에 실행하는 경우에 유용합니다.</p>
<pre><code class="python">
import gevent
from gevent.pool import Pool
pool = Pool(2)
def hello_from(n):
print('Size of pool %s' % 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들이 동시에 접근하거나 실행되는 것을 제한하는 저수준의 synchronization primitive입니다. Semaphore는 <code>acquire</code>와 <code>release</code>라는 함수를 가지고 있습니다. Semaphore가 acquire 되거나 release되는 숫자의 차이는 Semaphore bound라고 불립니다. Semaphore bound가 0에 도달하면 다른 Greenlet이 release 할 때까지 block 됩니다.</p>
<pre><code class="python">
from gevent import sleep
from gevent.pool import Pool
from gevent.coros import BoundedSemaphore
sem = BoundedSemaphore(2)
def worker1(n):
sem.acquire()
print('Worker %i acquired semaphore' % n)
sleep(0)
sem.release()
print('Worker %i released semaphore' % n)
def worker2(n):
with sem:
print('Worker %i acquired semaphore' % n)
sleep(0)
print('Worker %i released semaphore' % n)
pool = Pool()
pool.map(worker1, xrange(0,2))
pool.map(worker2, xrange(3,6))
</pre>
<p></code>
<pre><code class="python">
Worker 0 acquired semaphore
Worker 1 acquired semaphore
Worker 0 released semaphore
Worker 1 released semaphore
Worker 3 acquired semaphore
Worker 4 acquired semaphore
Worker 3 released semaphore
Worker 4 released semaphore
Worker 5 acquired semaphore
Worker 5 released semaphore
</pre></code></p>
<p>Semaphore bound가 1인 경우를 Lock이라고 합니다. Lock은 Greenlet이 하나만 실행되는 것을 보장합니다. Lock은 자원이 한 번에 하나의 Greenlet에 의해서만 사용되는 것을 보장하여야 할 때 사용됩니다.</p>
<h2 id="thread-locals">Thread Locals</h2>
<p>또한 Gevent는 Greenlet context 안에서 특정 변수를 지역 변수로 명시하는 것이 가능합니다. 이것은 내부적으로 Greenlet의 <code>getcurrent()</code> 값으로 private namespace key를 설정하는 방식으로 구현되어 있습니다.</p>
<pre><code class="python">
import gevent
from gevent.local import local
stash = local()
def f1():
stash.x = 1
print(stash.x)
def f2():
stash.y = 2
print(stash.y)
try:
stash.x
except AttributeError:
print("x is not local to f2")
g1 = gevent.spawn(f1)
g2 = gevent.spawn(f2)
gevent.joinall([g1, g2])
</pre>
<p></code>
<pre><code class="python">
1
2
x is not local to f2
</pre></code></p>
<p>gevent를 사용하는 많은 웹프레임워크들은 HTTP 세션 객체들을 gevent thread local 변수로 저장합니다. 예를 들어, Werkzeug 유틸리티 라이브러리와 해당 라이브러리의 proxy 객체를 사용하면 Flask 스타일의 request 객체를 만들 수 있습니다.</p>
<pre>
<code class="python">from gevent.local import local
from werkzeug.local import LocalProxy