[Python]코루틴(Coroutine)

코루틴(Coroutine)에 대해 알아보자

# 코루틴 : 단일(싱글) 스레드 환경에서 동작, 스택을 기반으로 동작하는 비동기 작업
# 쓰레드 : OS에서 관리, 시분할 비동기 작업, 교착 상태 발생가능성, 컨텍스트 스위칭 비용 발생

# 서브루틴 : 메인루틴 호출 -> 서브루틴에서 수행(흐름제어)
# 코루틴 : 루틴 실행 중 중지 -> 동시성 프로그래밍, 쓰레드에 비해 오버헤드 감소
# Python v3.5 이상 버전에서는 def -> async, yield -> await 으로 변경하여 사용가능하다.

# 코루틴 예제1
def coroutine1():
    print('>> coroutine started')
    i = yield
    print(f'>> coroutine received : {i}')


# 제네레이터 선언
cr1 = coroutine1()
print(cr1, type(cr1))
next(cr1) # yield 지점까지 서브루틴 수행
"""
<generator object coroutine1 at 0x102c54e40> <class 'generator'>
>> coroutine started
"""


# 기본 전달값은 = None, 메인루틴 -> 서브루틴으로 값을 전달할 수 있다.
# cr1.send(100)

# 잘못된 사용방법 : yield 구문전에 send문을 사용할 수 없다.
# cr2 = coroutine1()
# cr2.send(100)  --> 오류발생 (TypeError: can't send non-None value to a just-started generator)


# 코루틴 예제2
# GEN_CREATED : 처음 대기상태
# GEN_RUNNING : 실행 상태
# GEN_SUSPENDED : Yield 대기 상태
# GEN_CLOSED : 실행 완료 상태

def coroutine2(x):
    print(f'>> coroutine2 started : {x}')
    y = yield x
    print(f'>> coroutine2 received : {y}')
    z = yield x + y
    print(f'>> coroutine2 received : {z}')


cr3 = coroutine2(10)

from inspect import getgeneratorstate
print(getgeneratorstate(cr3))
print(next(cr3))
print(getgeneratorstate(cr3))
cr3.send(100)
"""
GEN_CREATED
>> coroutine2 started : 10
10
GEN_SUSPENDED
>> coroutine2 received : 100
"""
print()
print()


# 코루틴 예3
# v3.5 이상에서 StopIteration 자동처리

def coroutine3():
    for x in 'AB':
        yield x
    for y in range(1, 4):
        yield y


t1 = coroutine3()
print(next(t1))
print(next(t1))
print(next(t1))
print(next(t1))
print(next(t1))

t2 = coroutine3()
print(list(t2))
"""
A
B
1
2
3
['A', 'B', 1, 2, 3]
"""

print()

# coroutine3과 동일한 코드
def coroutine4():
    yield from 'AB'
    yield from range(1, 4)

t3 = coroutine4()
print(next(t3))
print(next(t3))
print(next(t3))
print(next(t3))
print(next(t3))
"""
A
B
1
2
3
"""

You may also like...

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다