# [Python] 비동기 프로그래밍

## 비동기 프로그래밍

---

- 프로그램의 흐름을 블록하지 않고 다른 작업을 계속 진행할 수 있도로고

- 하나의 작업이 완료될때까지 가디라지 않고 다른 작업을 진행

### 동기 vs 비동기 프로그래밍

> Google Colab의 환경에서는 이미 기본적으로 이벤트 루프가 실행 중입니다. 이 이벤트 루프는 Google Colab 환경의 비동기 작업을 처리하기 위해 사용됩니다. 그러므로 Google Colab에서는 `asyncio.run()` 함수를 직접 호출하면 “cannot be called from a running event loop”와 같은 에러 메시지가 출력됩니다. 이를 해결하려면 아래와 같은 코드를 추가해야합니다. 

```javascript
!pip install nest_asyncio
```

```javascript
import nest_asyncio
nest_asyncio.apply()
```

**동기 프로그래밍**

```javascript
import time
def job(number):
    print(f"Job {numer} started")
    time.sleep(1) # 매우 오래 걸리는 작업, 일반 sleep은 CPU를 쉬게 합니다.
    print(f"Job {numer} completed")

job(1)
job(2)
job(3)
```

- 코드가 순차적으로 실행되며, 특정 작업이 완료될 때까지 프로그램이 기다리는 방식

**비동기 프로그래밍**

```javascript
import asyncio

async def job(number):
    print(f"Job {number} started")
    await asyncio.sleep(1) # 매우 오래 걸리는 작업
    print(f"Job {number} completed")

async def main():
    await asyncio.gather(job(1), job(2), job(3)) # await asyncio.wait([job(1), job(2), job(3)])

asyncio.run(main())
print("hello world")
```

```javascript
# 코랩에서만 사용 가능한 코드
import asyncio

async def job(number):
    print(f"Job {number} started")
    await asyncio.sleep(1) # 매우 오래 걸리는 작업
    print(f"Job {number} completed")

asyncio.run(job(1))
asyncio.run(job(2))
asyncio.run(job(3))
```

- 동시에 여러 작업을 진행할 수 있다

- 이벤트 루프와 콜백 함수 등을 활용하여 작업을 관리

## 코루틴

---

```javascript
# 일반 함수
def job():
    print('job')
```

```javascript
async def job():
    print('job')

print(job) # <function job ast ...>
job() # <coroutine object job at ...>, print('job')이 실행되지 않습니다!
```

```javascript
asyn def main():
    return awati job()

main() # <coroutine object main at ...>
print(await main() # None
```

- `async`를 붙임 함수는 코루틴 함수

- `await` 키워드를 만나면 코루틴 실행을 잠시 중단, 코루틴 작업이 완료될 때까지 기다린 후 결과를 반환

**주요 개념**

- `async def`: 코루틴 함수를 선언, 함수를 비동기적으로 실행할 수 있는 코루틴 객체 반환

- `await()`: 코루틴의 작업이 완료될 때까지 기다린 후 결과를 반환

- `asyncio.run()`: 코루틴을 실행하는 함수, 이벤트 루프를 생성하고 주어진 코루틴을 실행 후 이벤트 루프를 닫는다

- `asyncio.gather()`

For the site tree, see the [root Markdown](https://slashpage.com/yerim-devnote.md).
