Python/개념

2024-06-03 30. 파이썬 비동기

nomad06 2024. 6. 3. 10:51

1. 동기(Synchronous)

  • 작업이 순차적으로 실행되는 것
  • 하나의 작업이 끝나기 전에는 다음 작업을 시작하지 않음
def func1():
    print('1')
    print('2')
    print('3')

def main():
    func1()
main()

 

import time
# main 함수는 smile 함수가 종료될 때까지 기다림
# smile 함수가 종료되기 전에 main 함수에서 더 처리해야 할 일이 있다면 ??? -> 비동기
def smile():
    time.sleep(1)
    print('😊😊😊😊😊')

def main():
    smile()  # 1초 쉬고 찍고
    smile()  # 1초 쉬고 찍고
print(f"시작: {time.strftime('%X')}")
main()
print(f"끝: {time.strftime('%X')}")  # 2초 차이

 

 

2. 비동기(Asynchonous)

  • 작업이 병렬적으로 실행되는 것
  • 시간이 오래 걸리는 작업을 기다리는 동안 다른 작업을 수행

✔ RuntimeError: asyncio.run() cannot be called from a running event loop

  • asyncio.run() 함수는 새로운 이벤트 루프를 생성하고 주어진 서브루틴(코루틴)을 실행하기 위해 사용
  • 코랩이나 주피터 노트북 환경에서는 이미 이벤트 루프가 내부적으로 실행중이기 때문에 asyncio.run()를 호출하면 에러가 발생
  • 따라서 아래 모듈을 import하고 메서드 호출해야 함
    import nest_asyncio
    nest_asyncio.apply()
import nest_asyncio
nest_asyncio.apply()
import asyncio
async def smile():
    await asyncio.sleep(1)
    print('😊😊😊😊😊')

async def main():
    # 여러 비동기 작업을 동시에 실행하고 그 결과를 반환하는데 사용
    await asyncio.gather(
        smile(),
        smile()
    )
print(f"시작: {time.strftime('%X')}")
asyncio.run(main())
print(f"끝: {time.strftime('%X')}")  # 1초 차이
# 처음 에러남
# import nest_asyncio
# nest_asyncio.apply()
# RuntimeError: asyncio.run() cannot be called from a running event loop