728x90
반응형
41.코루틴(Corutine)
Cooperative routine
서로 협력하는 루틴
즉, 메인 루틴과 서브 루틴처럼 종속된 관계가 아니라 서로 대등한 관계이며 특정 시점에 상대방의 코드를 실행
def add(a, b): # 서브루틴
c = a + b
print(c)
print('add 함수')
def calc(): # 메인루틴
add(1, 2) # 서브루틴
print('calc 함수')
calc() # 메인루틴
코루틴은 함수가 종료되지 않은 상태에서 메인 루틴의 코드를 실행한 뒤 다시 돌아와서 코루틴의 코드를 실행한다.
따라서 코루틴이 종료되지 않았으므로 코루틴의 내용도 계속 유지된다.
코루틴은 진입점(함수의 코드를 실행하는 지점)이 여러개인 함수이다.
41.1 코루틴 값 보내기
- 제너레이터의 특별한형태
- 제너레이터는 yield로 값을 발생시켰지만, 코루틴은 yield로 값을 받아올 수 있다.
- 코루틴 객체.send(값)
- 변수 = (yield)
def number_coroutine():
while True: # 코루틴을 계속 유지하기 위해 무한 루프 사용
x = (yield) # 코루틴 바깥에서 값을 받아옴. yield를 괄호로 묶어야 함
print(x)
co = number_coroutine()
next(co) # 코루틴 안의 yield까지 코드 실행(최초 실행)
co.send(1) # 코루틴에 숫자 1을 보냄
co.send(2) # 코루틴에 숫자 2을 보냄
co.send(3) # 코루틴에 숫자 3을 보냄
==========================
1
2
3
41.2 코루틴 바깥으로 값 전달
def sum_coroutine():
total = 0
while True:
x = (yield total)
total += x
co = sum_coroutine()
print(next(co))
print(co.send(1))
print(co.send(2))
print(co.send(3))
==========================
0
1
3
6
41.3 코루틴을 종료하고 예외 처리
def number_coroutine():
while True:
x = (yield)
print(x, end=' ')
co = number_coroutine()
next(co)
for i in range(20):
co.send(i)
co.close()
==========================
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# GeneratorExit 예외 처리
def number_coroutine():
try:
while True:
x = (yield)
print(x, end=' ')
except GeneratorExit:
print()
print('코루틴 종료')
co = number_coroutine()
next(co)
for i in range(20):
co.send(i)
co.close()
==========================
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
코루틴 종료
def sum_coroutine():
try:
total = 0
while True:
x = (yield)
total += x
except RuntimeError as e:
print(e)
yield total
co = sum_coroutine()
next(co)
for i in range(20):
co.send(i)
print(co.throw(RuntimeError, '예외로 코루틴 끝내기'))
==========================
예외로 코루틴 끝내기
190
41.4 하위 코루틴의 반환값 가져오기
def accumulate():
total = 0
while True:
x = (yield)
if x is None:
return total
total += x
def sum_coroutine():
while True:
total = yield from accumulate()
print(total)
co = sum_coroutine()
next(co)
for i in range(1, 11):
co.send(i)
co.send(None)
for i in range(1, 101):
co.send(i)
co.send(None)
==========================
55
5050
41.6 연습문제 : 문자열 검색 코루틴 만들기
def find(word):
result = False
while True:
line = (yield result)
result = word in line
f = find('Python')
next(f)
print(f.send('Hello, Python'))
print(f.send('Hello, world'))
print(f.send('Python, Script'))
==========================
True
False
True
728x90
반응형
'Language > Python' 카테고리의 다른 글
[코딩도장]43.정규표현식 (0) | 2022.04.14 |
---|---|
[코딩도장]42.데코레이터 (0) | 2022.04.12 |
[코딩도장]40.제너레이터 (0) | 2022.04.06 |
[코딩도장]39. 이터레이터 (0) | 2022.04.05 |
[코딩도장]38.예외처리 (0) | 2022.04.04 |