성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] 제가 큰 실수를 했군요. ^^; Delegate를 통한 Bein...
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
[정성태] 저렇게 조각 코드 말고, 실제로 재현이 되는 예제 프로젝트를 압...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>파이썬 - async/await 기본 사용법</h1> <p> C# 개발자라면, 파이썬의 async/await를 <a target='tab' href='https://www.sysnet.pe.kr/2/0/13422'>유사한 경험으로 사용</a>할 수 있습니다. 우선, 간단하게 콘솔 앱으로 예제를 작성해 볼까요? ^^<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > <span style='color: blue; font-weight: bold'>async def main_async()</span>: print('async called') <span style='color: blue; font-weight: bold'>await main_async()</span> """ 실행 결과: File "C:\test\main.py", line 6 await main_async() ^ SyntaxError: 'await' outside function """ </pre> <br /> 위의 코드를 실행하면 "실행 결과"에서 보는 바대로 await을 함수 밖에서 사용했다고 오류가 발생합니다. 그래서 이것을 함수에 담아서 다시 호출해 보면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > import time async def do_something(delay: int=0): time.sleep(delay) return delay <span style='color: blue; font-weight: bold'>def main(): await do_something(3)</span> main() """ 실행 결과: File "/home/testusr/main.py", line 10 await do_something(3) ^ SyntaxError: 'await' outside async function """ </pre> <br /> 이번엔 async 함수가 아닌 곳에서 사용했다고 나옵니다. 그렇다면 main 함수를 async로 만들어야 하지만,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > <span style='color: blue; font-weight: bold'>async</span> def main(): await do_something(3) main() """ 실행 결과: /home/testusr/main.py:12: RuntimeWarning: coroutine 'main' was never awaited main() RuntimeWarning: Enable tracemalloc to get the object allocation traceback """ </pre> <br /> 그럼 main 함수가 비동기 호출 처리가 안 되었다는 불평을 하게 되므로, 결국 main 호출도 "await main()"으로 바꿔야 하고 문제가 다시 원점으로 돌아가게 됩니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> C#은 Main 메서드 시작부터 async Main으로 만드는 것이 가능하지만 파이썬은 그에 대한 처리는 없기 때문에 이런 경우 라이브러리의 도움을 받아야 합니다. 실제로 최초의 async 진입 함수를 asyncio.run 등의 함수를 이용해 실행하면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > import time import asyncio <span style='color: blue; font-weight: bold'>async def main_async():</span> print('async calling', time.strftime('%X')) time.sleep(5) print('async called', time.strftime('%X')) <span style='color: blue; font-weight: bold'>asyncio.run(main_async())</span> """ 실행 결과: async calling 14:06:08 async called 14:06:13 """ </pre> <br /> 아무런 문제 없이 코드가 수행됩니다. 또한 await을 순차적으로 비동기 처리하는 것은 C#의 체계와 같습니다. 그래서 아래의 코드는 총 9초를 소요하게 되는데요,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > import time import asyncio async def do_something(delay: int=0): time.sleep(delay) async def main_async(): print('async calling', time.strftime('%X')) <span style='color: blue; font-weight: bold'>await do_something(3) await do_something(6)</span> print('async called', time.strftime('%X')) # 9초 지나서 실행 # 아래에서 다루겠지만, do_something 함수 내부의 코드 문제로 비동기 처리와 무관하게 9초가 걸립니다. asyncio.run(main_async()) </pre> <br /> 그렇다면 병렬처리는 어떻게 할 수 있을까요? C#의 경우라면 개별 호출을 Task로 받아 await을 별도로 진행하거나 Task.WhenAll로 받을 수 있는데요, 파이썬도 유사한 사용자 경험을 제공합니다.<br /> <br /> 실제로 해볼까요? ^^ 우선, C#처럼 다음과 같이 코딩하면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > task1 = do_something(3) # 동기 호출: 이곳에서 time.sleep(3) 코드 동작 task2 = do_something(6) # 동기 호출: 이곳에서 time.sleep(6) 코드 동작 await task1 await task2 </pre> <br /> 위의 호출은 총 9초가 소요됩니다. 사실 "task1 = do_something(...)" 형식이 동기 호출이든 비동기 호출이든 상관없이 저 코드는 총 9초가 소요됩니다. 왜냐하면 do_something의 내부에 있는 time.sleep이 동기적으로 호출되기 때문에 그것을 호출하는 측의 스레드가 그대로 묶이기 때문입니다.<br /> <br /> 따라서, 이 문제를 없애려면 time.sleep도 비동기 버전을 사용해야 합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > async def do_something(delay: int=0): <span style='color: blue; font-weight: bold'>await asyncio.sleep(delay)</span> task1 = do_something(3) # 동기 호출이지만 asyncio.sleep 비동기 호출로 3초를 대기하지 않고 제어 반환 task2 = do_something(6) # 동기 호출이지만 asyncio.sleep 비동기 호출로 6초를 대기하지 않고 제어 반환 await task1 # 이곳에서 비동기 3초 작업 대기 await task2 # 이미 3초가 흘렀으므로 남은 비동기 3초 대기 # 총 6초 소요 </pre> <br /> 보는 바와 같이, 이제야 원하는 대로 병렬 처리가 잘 되었습니다. (저렇게 보면 C#의 코드와 거의 같습니다.)<br /> <br /> 또한, 파이썬 역시 C#의 Task.WhenAll과 유사하게 병렬 처리를 위한 전용 함수인 asyncio.gather를 제공합니다. 따라서 이것을 이용하면 다음과 같이 재작성할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > # Can I use await on multiple functions at once? # <a target='tab' href='https://stackoverflow.com/questions/68733675/can-i-use-await-on-multiple-functions-at-once'>https://stackoverflow.com/questions/68733675/can-i-use-await-on-multiple-functions-at-once</a> import time import asyncio async def do_something(delay: int=0): await asyncio.sleep(delay) async def main_async(): print('async calling', time.strftime('%X')) <span style='color: blue; font-weight: bold'>await asyncio.gather(do_something(3), do_something(6))</span> # 6초 소요 print('async called', time.strftime('%X')) asyncio.run(main_async()) </pre> <br /> 참고로, gather의 경우 인자를 개별적으로 지정하는데, 인자가 포함된 리스트를 받는 wait 함수를 쓰는 것도 가능합니다. (<a target='tab' href='https://stackoverflow.com/questions/42231161/asyncio-gather-vs-asyncio-wait-vs-asyncio-taskgroup'>gather/wait</a>)<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > async def main_async(): print('async calling', time.strftime('%X')) jobs = <span style='color: blue; font-weight: bold'>[do_something(3), do_something(6)]</span> # 리스트로 전달 <span style='color: blue; font-weight: bold'>await asyncio.wait(jobs)</span> # 6초 소요 print('async called', time.strftime('%X')) </pre> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1473
(왼쪽의 숫자를 입력해야 합니다.)