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

'Python > 개념' 카테고리의 다른 글
2024_06-03 29. 데이터베이스와 MongoDB (0) | 2024.06.03 |
---|---|
2024-03-29 재귀 호출 (0) | 2024.03.29 |
2024-03-22 과제 디렉토리 관리 프로그램 만들기 (0) | 2024.03.22 |
2024-03-22 주피터 노트북 설치, 디렉토리 관리 프로그램 (0) | 2024.03.22 |
2024-03-21 파일 입출력 라이브러리 (0) | 2024.03.21 |