반응형

코루틴과 데이터를 교환해서 처리해 보자.

 

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
import time
 
def MyCoroutine():
    num = 0
    while True:
        x = yield num
        num += 1
        print(x)
        time.sleep(0.5)
 
co = MyCoroutine()
next(co)
time.sleep(1)
# 코루틴을 시작하고 yield 명령에서 대기한다.
 
print(co.send(100))
time.sleep(1)
# 코루틴에 100을 전달(x에 100 대입)하고 num을 받아서 출력한다.
# num 값은 yield 명령이 실행되는 시점에 결정된 값(0)이 아니고
# 코루틴이 끝나는 시점에 결정된 값(1)이 전달된다.
 
print(co.send(200))
time.sleep(1)
# 코루틴에 200을 전달(x에 200 대입)하고 num을 받아서 출력한다.
 
next(co)
# 코루틴에 아무 값도 전달하지 않고(그래서 None이 출력된다) 다음
# yield 까지 진행하고 받아온 num 값은 무시.
 
print(next(co))
# 마찬가지로 코루틴에 아무 값도 전달하지 않고 다름 yield 까지 진행.
# 이번엔 num 값을 받아서 출력한다.
 
co.close()
 

 

 

 

반응형
Posted by J-sean
:
반응형

파이썬에서 여러 작업을 코루틴으로 동시에 진행해 보자.

 

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
import asyncio
import time
 
async def show_text(text, delay):
    for i in range(5):
        print(text + " " + str(i))
        await asyncio.sleep(delay)
        # coroutine asyncio.sleep(delay, result=None)
        # Block for delay seconds. If result is provided,
        # it is returned to the caller when the coroutine
        # completes. sleep() always suspends the current
        # task, allowing other tasks to run.
    return text
 
async def main():
    #result = await asyncio.gather(
    #    show_text("first", 0.5),
    #    show_text("second", 0.5),
    #    show_text("third", 1)
    #    )
    #print(result)
 
    task1 = asyncio.create_task(show_text("first"0.5))
    task2 = asyncio.create_task(show_text("second"0.5))
    task3 = asyncio.create_task(show_text("third"1))
    # The asyncio.create_task() function to run coroutines
    # concurrently as asyncio Tasks.
 
    await task1
    await task2
    await task3
    # Awaiting on a coroutine.
 
    print("result: " + task1.result())
    print("result: " + task2.result())
    print("result: " + task3.result())
    
if __name__ == "__main__":
    start = time.time()
    asyncio.run(main())
    # The asyncio.run() function to run the top-level
    # entry point “main()” function.
    end = time.time()
    print(end - start)
 

 

 

총 소요시간은 5초이다.

첫 번째, 두 번째, 세 번째 작업의 소요시간 총 합이 아닌, 가장 긴 작업 시간을 가진 세 번째 작업의 소요시간인 5초가 걸린다.

 

Coroutines and Tasks

 

반응형
Posted by J-sean
: