본문 바로가기
프로그래밍

비동기 프로그래밍과 쓰레드

by YuminK 2023. 11. 13.

Java의 쓰레드, Kotlin의 Coroutine, C#의 쓰레드, Task

Dart의 async, await, Future, Javascript의 async, await, Promise

 

다양한 비동기 프로그래밍을 접해본 경험이 있으나 나는 비동기 프로그래밍과 멀티쓰레드의 차이를 잘 모르고 있더라. 그래서 이번에 관련 내용을 학습했다. 

 

동기와 비동기

동기는 프로그램의 흐름이 순차적인 것이고 비동기는 프로그램의 흐름이 순차적이지 않은 것이다. 즉, 순서를 보장하지 않는다. 비동기 프로그래밍은 쓰레드를 사용하여 구현되기도 하고, 싱글 쓰레드 기반으로 처리되기도 한다. 

 

자바스크립트에서는 이러한 문제를 Promise를 이용하여 해결한다. 나는 Promise같은 비동기에 대한 처리가 내부적으로는 Thread를 사용하는 것인지 궁금했다. 

 

프로미스의 동작은 자바(쓰레드 풀링을 사용하는 코드)와 다르며, 분리된 스레드를 필요로 하지 않는다.

 

Promises were invented to help manage asynchronous operations. Promises themselves do not need threads in order to do that.

 

What it looks like you are seeing in your Java code is code that helps run regular tasks in a separate thread (to give synchronous operations some asynchronous-type behavior). That is not what promises do. So, if you already have asynchronous operations in your environment, you would not need this type of code in order to use promises.

https://stackoverflow.com/a/25086098

 

C#의 Task는 내부에 존재하는 쓰레드 풀링을 사용하도록 되어 있다.

다음 내용에 따르면 쓰레드 풀을 사용하지 않고 싱글 쓰레드 기반으로 실행되는 경우도 있다고 한다. 

 

.net run-time behind the scene tries to minimize the number thread to be used. Sometimes it runs in single threaded asynchronous mode

https://codewala.net/2015/08/17/asynchronous-programming-with-async-and-await-explained/

 

비동기와 동기에 대해 자세히 다루고 있는 글이다. 

해당 포스팅의 내용에 따르면 싱글 쓰레드에서 여러 태스크를 오가며 실행 흐름을 제어할 수 있다고 한다.

 

싱글 쓰레드, 멀티 쓰레드 환경과는 별개로 동기적인 처리/비동기적 처리가 가능하다.

https://codewala.net/2015/07/29/concurrency-vs-multi-threading-vs-asynchronous-programming-explained/

 

운영체제의 인터럽트는 비동기 이벤트 처리를 가능하게 한다고 한다. 

 

Interrupts allow the CPU to deal with asynchronous events. In the regular fetch-and-execute cycle, things happen in a predetermined order; everything that happens is "synchronized" with everything else. Interrupts make it possible for the CPU to deal efficiently with events that happen "asynchronously," that is, at unpredictable times.

https://math.hws.edu/javanotes/c1/s2.html

 

결론

단일 쓰레드 환경에서도 비동기 프로그래밍이 가능하다. 프로그래밍 언어에 따라 쓰레드를 사용하여 실행 흐름을 명시적으로 나눠야 하는 경우와 그렇지 않은 경우가 있는 것으로 보인다. 내부구현에 따라 쓰레드 풀을 사용하여 처리할 수도 있고, 단일 쓰레드 환경에서 event를 모니터링 하는 방식으로 구현될 수도 있다. 언어마다 달라서 하나씩 찾아보는 게 좋을 것 같다. 단일 쓰레드에서 처리하든, 쓰레드 풀링이든 둘 중에 하나일 것이다.

'프로그래밍' 카테고리의 다른 글

[Zigbee] FZ200BS 모듈 정리  (0) 2023.12.11
Socket vs WebSocket  (1) 2023.11.14
디자인 패턴에 대한 생각  (0) 2023.11.12
테스트 서버(윈도우) 설정 방법  (0) 2023.11.12
[Flutter, C#] .env 파일 추가  (1) 2023.10.23

댓글