💻 Programming

Concurrency

Concurrency

The concept of handling multiple tasks at the same time. Distinct from parallelism. Implemented with threads and coroutines.

📖 Detailed Explanation

Concurrency is a programming paradigm that handles multiple tasks as if they were progressing simultaneously in a logical sense. Even if only one task is actually executing at any given moment, rapid switching between tasks (context switching) makes it appear that multiple tasks are progressing at the same time.

Concurrency and parallelism are often confused, but they are clearly different concepts. Concurrency is about "dealing with multiple tasks," while parallelism is "executing multiple tasks at the same time." Concurrency is possible even on a single-core CPU, but parallelism can only be achieved on multiple cores.

Concurrency is implemented in various ways, including threads, processes, coroutines, and event loops. Threads are managed at the OS level and are heavyweight but allow true parallel execution, while coroutines are cooperatively scheduled at the user level, making them lightweight and efficient.

In practice, concurrency is used at the core of handling multiple requests on web servers, asynchronous I/O operations, keeping GUI applications responsive, and running background tasks. Modern languages such as Python's asyncio, JavaScript's Promise, Go's goroutines, and Java's Virtual Thread all provide strong concurrency support.

💻 Code Example

# Python asyncio를 활용한 동시성 처리 예제
import asyncio
import aiohttp
import time

# 1. 기본 코루틴과 동시성
async def fetch_url(session, url):
    """비동기적으로 URL에서 데이터 가져오기"""
    async with session.get(url) as response:
        data = await response.text()
        print(f"완료: {url[:50]}... ({len(data)} bytes)")
        return data

async def main():
    urls = [
        "https://api.github.com",
        "https://httpbin.org/get",
        "https://jsonplaceholder.typicode.com/posts/1"
    ]

    start = time.time()

    async with aiohttp.ClientSession() as session:
        # 동시에 모든 요청 실행 (병렬 X, 동시성 O)
        tasks = [fetch_url(session, url) for url in urls]
        results = await asyncio.gather(*tasks)

    elapsed = time.time() - start
    print(f"\n총 소요 시간: {elapsed:.2f}초 (동시 처리)")
    print(f"순차 처리였다면 약 {len(urls) * 0.3:.2f}초 이상 소요")

# 2. 동시성 vs 순차 처리 비교
async def io_bound_task(name, delay):
    """I/O 바운드 작업 시뮬레이션"""
    print(f"[{name}] 시작...")
    await asyncio.sleep(delay)  # 비동기 대기 (다른 작업에 양보)
    print(f"[{name}] 완료! ({delay}초)")
    return name

async def concurrent_demo():
    """동시성 데모: 3개 작업이 동시에 진행"""
    print("=== 동시성 처리 ===")
    start = time.time()

    # 동시에 실행 - 총 2초 소요 (가장 긴 작업 기준)
    results = await asyncio.gather(
        io_bound_task("작업A", 2),
        io_bound_task("작업B", 1),
        io_bound_task("작업C", 1.5)
    )

    print(f"결과: {results}")
    print(f"소요 시간: {time.time() - start:.2f}초\n")

# 실행
asyncio.run(main())
asyncio.run(concurrent_demo())

🗣️ Say It Like This in Practice

💬 In a Meeting
"Concurrency handling is the key for this API gateway. We currently need to handle 5,000 requests per second, and if we implement it based on asyncio, memory efficiency is more than 10 times better than a thread pool, and we can also reduce context switching overhead."
💬 In an Interview
"To explain the difference between concurrency and parallelism: concurrency is one barista handling multiple orders by alternating between them, while parallelism is multiple baristas each handling their own orders at the same time. Concurrency is effective for I/O-bound tasks, and parallelism is effective for CPU-bound tasks."
💬 In a code review
"Here, creating individual tasks with asyncio.create_task instead of asyncio.gather makes error handling more flexible. And if you don't limit the number of concurrent executions with a semaphore, you may hit the external API rate limit."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Race Condition

It occurs when multiple tasks access a shared resource at the same time. Use synchronization mechanisms such as mutexes, semaphores, and locks, or use immutable data structures where possible.

❌
Deadlock

It is a state in which two or more tasks wait indefinitely for each other's resources. Prevent it by keeping the lock acquisition order consistent and setting timeouts.

❌
Confusing Concurrency and Parallelism

Due to Python's GIL (Global Interpreter Lock), threading cannot achieve true parallel execution for CPU-bound tasks. Use multiprocessing for CPU tasks and asyncio for I/O tasks.

✅
Choosing an Appropriate Concurrency Pattern

Use async/await for I/O-bound tasks and multiprocessing for CPU-bound tasks, and consider Go's goroutines or Rust's tokio if high performance is required. Choosing the right tool for the situation is important.

🔗 Related Terms

📚 Learn More