Python의 비동기 프로그래밍
비동기 프로그래밍은 많은 프로세스가 다음 프로세스로 진행하기 전에 완료될 때까지 기다리지 않고 동시에 독립적으로 수행할 수 있도록 하는 프로그래밍 패러다임입니다 . 이 블로그 포스트에서는 비동기 프로그래밍이 무엇인지, 파이썬에서 어떻게 사용하는지 살펴보겠습니다.
비동기 프로그래밍이란 무엇입니까?
동기식 프로그래밍에서 컴퓨터는 명령을 순차적으로 실행하여 다음 작업으로 진행하기 전에 작업이 완료될 때까지 실행을 차단합니다.
반면에 비동기 프로그래밍은 프로그램이 하나의 작업을 시작한 다음 원래 작업이 완료될 때까지 실행을 중단하지 않고 다른 작업을 계속할 수 있도록 합니다.
비동기 프로그래밍은 네트워크 I/O 또는 데이터베이스 작업과 같은 프로세스를 완료하는 데 오랜 시간이 걸릴 수 있는 상황에서 특히 유용합니다. 비동기식 프로그래밍은 프로그램이 느린 작업이 완료되기를 기다리는 동안 다른 작업을 계속할 수 있도록 하여 소프트웨어 응용 프로그램의 성능과 응답성을 높이는 데 도움이 될 수 있습니다.
사용된 프로그래밍 언어와 프레임워크에 따라 콜백, 약속 또는 async/await 키워드와 같은 다양한 전략을 사용하여 비동기식 프로그래밍을 수행할 수 있습니다.
비동기 프로그래밍과 다중 처리의 차이점
비동기 프로그래밍과 멀티프로세싱의 주요 차이점은 비동기 프로그래밍을 통해 단일 스레드 내에서 비차단 작업이 발생할 수 있는 반면 멀티프로세싱은 많은 코어 또는 프로세스를 사용하여 작업을 동시에 완료한다는 것입니다.
비동기 프로그래밍과 스레딩의 차이점
비동기 프로그래밍과 스레딩의 주요 차이점은 비동기 프로그래밍은 단일 스레드를 사용하여 비차단 작업을 허용하는 반면 스레딩은 여러 스레드를 사용하여 여러 작업을 병렬로 수행한다는 것입니다.
차이점에 대한 자세한 정보: 트레딩 vs 멀티프로세싱 vs 비동기 프로그래밍
Asyncio를 사용하는 방법?
먼저 한 번에 작업을 시작하고 완료하는 간단한 프로그램을 만들어 봅시다.
import time
import asyncio
def do_job(s):
print(f"{s} started")
await asyncio.sleep(1)
print(f"{s} done")
def main():
start = time.perf_counter()
todo = ["Job A", "Job B", "Job C"]
for job in todo:
do_job(job)
end = time.perf_counter()
print(f"Took: {end-start:.3f} seconds")
main()
# OUTPUT
# Job A started
# Job Adone
# Job B started
# Job B done
# Job C started
# Job C done
# Took: 3.009 seconds
코루틴 생성 및 실행
코루틴은 실행 중 다양한 시간에 중단 및 재개할 수 있는 함수 유형입니다. 즉, 코루틴을 사용하면 중단될 수 있는 코드를 작성하고 다른 작업을 수행한 다음 중단된 위치에서 다시 시작할 수 있습니다.
코루틴을 생성하려면 키워드 async앞에 키워드를 사용해야 합니다 def. 코루틴을 호출한다고 해서 실행하려는 함수가 호출되는 것은 아닙니다. 작업을 생성합니다.
import time
import asyncio
async def do_job(s):
...
async def main():
...
main()
asyncio.run(main())
이 코드를 실행하면 다음과 같은 오류가 발생할 수 있습니다.
RuntimeWarning: coroutine '...' was never awaited
import time
import asyncio
async def do_job(s):
print(f"{s} started")
await asyncio.sleep(1)
print(f"{s} done")
async def main():
start = time.perf_counter()
todo = ["Job A", "Job B", "Job C"]
for job in todo:
await do_job(job)
end = time.perf_counter()
print(f"Took: {end-start:.3f} seconds")
asyncio.run(main())
# OUTPUT
# Job A started
# Job A done
# Job B started
# Job B done
# Job C started
# Job C done
# Took: 3.009 seconds
await asyncio.sleep(1)
tasks = [asyncio.create_task(do_job(item)) for item in todo]
done, pending = await asyncio.wait(tasks)
import time
import asyncio
async def do_job(s):
print(f"{s} started")
await asyncio.sleep(1)
print(f"{s} done")
async def main():
start = time.perf_counter()
todo = ["Job A", "Job B", "Job C"]
tasks = [asyncio.create_task(do_job(item)) for item in todo]
done, pending = await asyncio.wait(tasks)
end = time.perf_counter()
print(f"Took: {end-start:.3f} seconds")
asyncio.run(main())
# OUTPUT
# Job A started
# Job B started
# Job C started
# Job A done
# Job B done
# Job C done
# Took: 1.009 seconds
파이썬에서 비동기 프로그래밍에 대한 자세한 정보를 얻기 위한 비디오를 볼 수 있습니다. ( 비동기 Python 소개 | 웹 크롤러 작성 )

![연결된 목록이란 무엇입니까? [1 부]](https://post.nghiatu.com/assets/images/m/max/724/1*Xokk6XOjWyIGCBujkJsCzQ.jpeg)



































