💻 Programming

Concurrency

Concurrency

The concept of handling multiple tasks at the same time. Unlike parallelism, it is logical simultaneous execution. Implemented with threads and coroutines.

📖 Detailed Explanation

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.

💻 Code Example

Python
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초

🗣️ Examples of Practical Conversations

Backend developer
"We call 3 external APIs for every user request, and doing it sequentially makes the response take as long as 3 seconds."
Senior developer
"If you make the calls in parallel using concurrency, you can reduce it to about the response time of the slowest API. In Python, try asyncio.gather."
Backend developer
"There's logic that combines the results — should everything fail if one of them fails?"
Interviewer
"Please explain the difference between concurrency and parallelism."
Candidate
"Concurrency makes multiple tasks appear to be handled simultaneously by interleaving their progress. Parallelism actually executes multiple tasks at the same time. On a single core, only concurrency is possible, while parallelism is possible on multiple cores."
Interviewer
"What is a race condition, and how do you prevent it?"
Candidate
"It is a phenomenon where, when two or more threads access a shared resource at the same time, the result varies depending on the execution order. It is prevented by using a mutex for mutual exclusion, using atomic operations, or using immutable data structures."

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

Reviewer
"In this code, multiple threads are appending to the same list. A Python list's append is atomic, but a race condition can occur when it is combined with other operations."
Author
"Using queue.Queue or protecting it with a Lock would be safer."
Reviewer
"Yes, and if possible, a design that minimizes shared state between threads is better. Have the results returned and combine them in the main thread."

⚠️ Cautions

🔗 Related Terms

📚 Learn More