비동기 모델
- 여러 작업이 동시에 일어날 수 있도록 지원.
- 실행 시간이 긴 함수 사용 시, 실행 흐름을 차단하지 않음. → 프로그램 계속 실행.
- 추가로, 해당 작업 완료 후,
결과값접근 가능.
- 추가로, 해당 작업 완료 후,
예제
- 네트워크를 통해 두 개 파일 fetch 후 결합하는 프로그램
- 비동기적 처리 방법 :
별도의 Thread- 첫 번째 스레드 → 첫 번째 파일
fetch - 두 번째 스레드 → 첫 번째 스레드와 상관 없이 두 번째 파일 가져오기 수행.
- 두 스레드 종료 후 동기화하여 결과 결합.
- 첫 번째 스레드 → 첫 번째 파일
- 비동기적 처리 방법 :
-
두 번째 예시 : 파일 요청 + 많은 연산 프로그램
단일 스레드 방식의 또 다른 예로는 운영체제(OS)에 파일을 요청하는 동시에 수학 연산을 수행해야 하는 프로그램을 들 수 있습니다. 비동기 시스템에서 프로그램은 OS에 파일을 요청한 후, 파일이 준비되기를 기다리는 동안 CPU에서 실행될 수학 연산으로 제어권을 반환합니다.
비동기 프로그래밍의 한 가지 접근 방식은 느린 작업을 수행하는 함수를 만들고, 여기에 추가 인자로 **콜백 함수(callback function)**를 전달하는 것입니다. 작업이 시작되고 완료되면, 그 결과를 가지고 콜백 함수가 호출됩니다.
3. What is Multithreading Programming? (멀티스레딩 프로그래밍이란 무엇인가?)
**멀티스레딩(Multithreading)**은 하나 이상의 순차적인 명령어 세트(스레드)를 동시에 또는 병렬로 실행하는 것을 의미합니다.
Multithreading refers to executing one or more sequential sets of instructions (threads) concurrently or in parallel.
단일 프로세서에서 멀티스레딩은 병렬로 실행되는 것과 같은 착각을 불러일으킵니다. 실제로는 프로세서가 스케줄링 알고리즘을 사용하여 실행 주체를 빠르게 전환하고 있는 것입니다. 혹은 외부 입력(인터럽트)과 스레드에 부여된 우선순위의 조합에 따라 전환이 이루어집니다.
On a single processor, multithreading creates the illusion of running in parallel. In reality, the processor uses a scheduling algorithm to quickly switch between execution subjects, or the switch occurs based on a combination of external input (interrupts) and priorities assigned to the threads.
반면, 다중 프로세서 코어 환경에서 스레드는 진정한 병렬성을 가집니다. 개별 마이크로프로세서들이 협력하여 결과를 더 효율적으로 도출해 냅니다. 즉, 여러 개의 병렬적이고 동시적인 작업들이 한 번에 실제로 일어납니다.
On the other hand, in a multi-processor core environment, threads have true parallelism. Individual microprocessors work together to produce results more efficiently. In other words, multiple parallel and simultaneous tasks actually happen at once.
A basic example of multithreading is downloading two files from two different tabs in a web browser. Each tab uses a new thread to download the requested file. No tab waits for the other one to finish, they are downloading concurrently.
(멀티스레딩의 기본적인 예는 웹 브라우저의 서로 다른 두 탭에서 두 개의 파일을 다운로드하는 것입니다. 각 탭은 요청된 파일을 다운로드하기 위해 새로운 스레드를 사용합니다. 어떤 탭도 다른 탭이 끝나기를 기다리지 않으며, 동시에 다운로드됩니다.)
The following picture shows a simple explanation of concurrent execution of a multithreaded application: (다음 그림은 멀티스레드 애플리케이션의 동시 실행에 대한 간단한 설명을 보여줍니다:)

4. Asynchronous vs Multithreading (비동기 vs 멀티스레딩)
From the definitions we just provided, we can see that multithreading programming is all about concurrent execution of different functions. Async programming is about non-blocking execution between functions, and we can apply async with single-threaded or multithreaded programming. (방금 제공한 정의를 통해, 멀티스레딩 프로그래밍은 서로 다른 함수들의 동시 실행에 관한 것임을 알 수 있습니다. 비동기 프로그래밍은 함수 간의 논블로킹(non-blocking) 실행에 관한 것이며, 단일 스레드 또는 멀티스레드 프로그래밍 모두에 비동기를 적용할 수 있습니다.)
So, multithreading is one form of asynchronous programming. (따라서 멀티스레딩은 비동기 프로그래밍의 한 형태입니다.)
Let’s take a simple analogy; you have a friend, and you decided to make dinner together. (간단한 비유를 들어보겠습니다. 당신과 친구가 함께 저녁 식사를 만들기로 했습니다.)
Async is when you say to your friend, “You go to the store and buy pasta. Let me know when you get back, to make dinner together. Meanwhile, I’ll prepare sauce and drinks.” (**비동기(Async)**는 당신이 친구에게 “가게에 가서 파스타를 사와. 돌아오면 나에게 알려줘, 같이 저녁 만들게. 그동안 나는 소스와 음료를 준비할게.”라고 말하는 것과 같습니다.)
Threading is, “You boil the water. I’ll heat the tomato sauce. While the water is boiling, ask me and I’ll put the pasta in. When the sauce is hot, you can add cheese. When both are done, I’ll sit down and you serve dinner. Then we eat.”. In the threading analogy, we can see the sequence of “When, Do” events, which represent the sequential set of instructions per each person (thread). (**스레딩(Threading)**은 “너는 물을 끓여. 나는 토마토 소스를 데울게. 물이 끓는 동안 나에게 물어보고 내가 파스타를 넣을게. 소스가 뜨거워지면 네가 치즈를 넣을 수 있어. 둘 다 다 되면 내가 앉을 테니 네가 저녁을 차려줘. 그러고 나서 먹자.”입니다. 스레딩 비유에서는 각 사람(스레드)에 대한 순차적인 명령어 세트를 나타내는 “언제, 무엇을 할지” 이벤트의 시퀀스를 볼 수 있습니다.)
From that analogy, we can conclude that Multithreading is about workers, Asynchronous is about tasks. (이 비유를 통해 멀티스레딩은 작업자(worker)에 관한 것이고, 비동기는 작업(task)에 관한 것이라고 결론지을 수 있습니다.)
5. Which One To Use? (어떤 것을 사용해야 할까?)
Choosing between the two programming models depends mainly on performance. (두 프로그래밍 모델 사이의 선택은 주로 ‘성능’에 달려 있습니다.)
Given all possible combinations between sync/async and single/multi-threading, which model should perform better? (동기/비동기 및 단일/멀티 스레딩 사이의 가능한 모든 조합 중에서 어떤 모델이 더 나은 성능을 낼까요?)
In a nutshell, for large scale applications with a lot of I/O operations and different computations, using asynchronous multithreading programming flow, will utilize the computation resources, and take care of non-blocking functions. This is the programming model of any OS! (요약하자면, 많은 I/O 작업과 다양한 연산이 포함된 대규모 애플리케이션의 경우, 비동기 멀티스레딩 프로그래밍 흐름을 사용하면 계산 자원을 최대한 활용하고 논블로킹 함수를 처리할 수 있습니다. 이것이 모든 운영체제(OS)의 프로그래밍 모델입니다!)
With more power, comes more responsibility! So if we decided to implement this model, we have to take care of different issues like race condition, deadlocks, shared resources, and callbacks events. (더 큰 힘에는 더 큰 책임이 따릅니다! 따라서 이 모델을 구현하기로 결정했다면 경쟁 상태(race condition), 교착 상태(deadlocks), 공유 자원 및 콜백 이벤트와 같은 다양한 문제를 관리해야 합니다.)
6. Conclusion (결론)
In this article, we showed the definitions of asynchronous programming and multithreaded programming, and then we saw the difference between them. (이 기사에서는 비동기 프로그래밍과 멀티스레드 프로그래밍의 정의를 살펴본 후, 그 차이점을 확인했습니다.)
Keep in mind that all terms and concepts in this article are technology agnostic. (이 기사의 모든 용어와 개념은 특정 기술에 국한되지 않는다는 점을 명심하십시오.)