Concurrency
Concurrency
The concept of handling multiple tasks at the same time. Unlike parallelism, it is logical simultaneous execution. Implemented with threads and coroutines.
Concurrency
The concept of handling multiple tasks at the same time. Unlike parallelism, it is logical simultaneous execution. Implemented with threads and coroutines.
Concurrency is a programming concept that makes multiple tasks appear to progress simultaneously at the logical level. Whereas parallelism means physically executing multiple tasks at the same time, concurrency handles tasks by switching rapidly between them so that they seem to progress at once.
Concurrency is possible even on a single-core CPU, because the operating system's scheduler rapidly switches between multiple processes or threads while running them. This allows other tasks to be handled during I/O wait times, which improves overall system efficiency.
The main challenge of concurrent programming is safe access to shared resources. To avoid problems such as race conditions, deadlocks, and livelocks, synchronization techniques such as mutexes, semaphores, and monitors are used. Recently, paradigms such as the actor model and CSP (Communicating Sequential Processes) have also become popular.
Each language offers a variety of concurrency models. JavaScript uses the event loop and async/await, Go uses goroutines and channels, Rust uses ownership-based safe concurrency, and Java uses threads and CompletableFuture.
import asyncio
import threading
import time
# 동시성 vs 순차 실행 비교
# 순차 실행 (느림)
def sequential_io():
for i in range(3):
time.sleep(1) # I/O 시뮬레이션
print(f"순차 작업 {i} 완료")
# 동시성: asyncio (단일 스레드, 협력적 멀티태스킹)
async def async_task(name, delay):
await asyncio.sleep(delay)
print(f"비동기 작업 {name} 완료")
return name
async def concurrent_io():
tasks = [
async_task("A", 1),
async_task("B", 1),
async_task("C", 1)
]
results = await asyncio.gather(*tasks) # 동시 실행
return results
# 동시성: 스레딩 (I/O 바운드 작업에 적합)
def threaded_task(name, delay):
time.sleep(delay)
print(f"스레드 작업 {name} 완료")
def concurrent_threads():
threads = [
threading.Thread(target=threaded_task, args=(f"T{i}", 1))
for i in range(3)
]
for t in threads:
t.start()
for t in threads:
t.join()
# 실행 비교
print("=== 순차 실행 ===")
start = time.time()
sequential_io()
print(f"소요 시간: {time.time() - start:.2f}초") # ~3초
print("\n=== 비동기 동시 실행 ===")
start = time.time()
asyncio.run(concurrent_io())
print(f"소요 시간: {time.time() - start:.2f}초") # ~1초
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free