💻 Programming

Multithreading

Multithreading

A programming technique that implements parallel processing by running multiple threads simultaneously within one process. It maximizes CPU utilization and improves responsiveness, but synchronization issues require care.

📖 Detailed Explanation

Multithreading is a parallel processing technique in which multiple threads run concurrently within a single process. Each thread has its own independent flow of execution and shares the process's memory space (heap and data area). This makes it possible to handle other tasks while waiting for I/O, or to use multicore CPUs efficiently. Typical examples are a web server handling thousands of requests at the same time, or a GUI application staying responsive even while background tasks are running.

Process vs. Thread: A process has its own independent memory space, and its creation and context switching costs are high. A thread, on the other hand, shares memory within a process, so its creation cost is low (usually 1/10 that of a process) and data sharing between threads is fast. However, this shared nature can cause synchronization problems. Modern applications mostly use a hybrid approach: separating into processes (microservices) and using threads within each process.

Synchronization mechanisms: These are tools for ensuring data consistency when multiple threads access shared resources. A mutex ensures that only one thread at a time accesses the critical section. A semaphore limits the number of threads that can access a resource concurrently, based on a counter. A condition variable makes a thread wait until a specific condition is met. Implementations differ by language, such as Java's synchronized, Python's Lock, and Go's sync.Mutex.

Practical applications: Web servers (Tomcat, Nginx worker) handle concurrent requests with thread pools. Database connection pools follow a pattern similar to thread pools. In data processing, large files are split into chunks for parallel processing, or processed in a distributed manner with the MapReduce pattern. In AI/ML, the PyTorch DataLoader performs data preprocessing with multiple threads to increase GPU utilization. The 2025 trend is the combination of async/await-based asynchronous programming with multithreading.

💻 Code Example

import threading
import time
from concurrent.futures import ThreadPoolExecutor

# 1. 기본 스레드 생성
def worker(name, delay):
    print(f"스레드 {name} 시작")
    time.sleep(delay)
    print(f"스레드 {name} 완료")

# 스레드 생성 및 실행
t1 = threading.Thread(target=worker, args=("A", 2))
t2 = threading.Thread(target=worker, args=("B", 1))

t1.start()
t2.start()
t1.join()  # 스레드 완료 대기
t2.join()

# 2. Lock을 사용한 동기화 (Race Condition 방지)
counter = 0
lock = threading.Lock()

def increment():
    global counter
    for _ in range(100000):
        with lock:  # 자동으로 acquire/release
            counter += 1

threads = [threading.Thread(target=increment) for _ in range(5)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print(f"최종 카운터: {counter}")  # 정확히 500000

# 3. ThreadPoolExecutor (실무 권장 패턴)
def fetch_url(url):
    # 실제로는 requests.get(url)
    time.sleep(0.5)
    return f"{url} 완료"

urls = ["url1", "url2", "url3", "url4", "url5"]

with ThreadPoolExecutor(max_workers=3) as executor:
    # map: 순서 보장, 결과 순차 반환
    results = list(executor.map(fetch_url, urls))

    # submit: Future 객체 반환, 비동기 처리
    futures = [executor.submit(fetch_url, url) for url in urls]
    for future in futures:
        print(future.result())

# 4. Queue를 활용한 생산자-소비자 패턴
from queue import Queue

task_queue = Queue()

def producer():
    for i in range(10):
        task_queue.put(f"task_{i}")
    task_queue.put(None)  # 종료 신호

def consumer():
    while True:
        task = task_queue.get()
        if task is None:
            break
        print(f"처리: {task}")
        task_queue.task_done()
import java.util.concurrent.*;
import java.util.concurrent.locks.*;

public class MultithreadingExample {

    // 1. Thread 클래스 상속
    static class MyThread extends Thread {
        private String name;

        public MyThread(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            System.out.println("스레드 " + name + " 시작");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            System.out.println("스레드 " + name + " 완료");
        }
    }

    // 2. Runnable 인터페이스 구현 (권장)
    static class MyRunnable implements Runnable {
        @Override
        public void run() {
            System.out.println("Runnable 실행: " +
                Thread.currentThread().getName());
        }
    }

    // 3. synchronized를 사용한 동기화
    static class Counter {
        private int count = 0;
        private final Object lock = new Object();

        // 메서드 전체 동기화
        public synchronized void incrementSync() {
            count++;
        }

        // 블록 동기화 (더 세밀한 제어)
        public void incrementBlock() {
            synchronized (lock) {
                count++;
            }
        }

        public int getCount() { return count; }
    }

    // 4. ReentrantLock 사용 (더 유연한 락)
    static class BetterCounter {
        private int count = 0;
        private final ReentrantLock lock = new ReentrantLock();

        public void increment() {
            lock.lock();
            try {
                count++;
            } finally {
                lock.unlock();  // 반드시 finally에서 해제
            }
        }

        // tryLock으로 데드락 방지
        public boolean tryIncrement() {
            if (lock.tryLock()) {
                try {
                    count++;
                    return true;
                } finally {
                    lock.unlock();
                }
            }
            return false;
        }
    }

    public static void main(String[] args) throws Exception {
        // 5. ExecutorService (실무 권장 패턴)
        ExecutorService executor = Executors.newFixedThreadPool(4);

        // Runnable 실행
        executor.execute(() -> System.out.println("Task 1"));

        // Callable로 결과 반환
        Future future = executor.submit(() -> {
            Thread.sleep(1000);
            return "Task 완료";
        });

        System.out.println("결과: " + future.get());  // 블로킹

        // CompletableFuture (Java 8+, 비동기 체이닝)
        CompletableFuture.supplyAsync(() -> "Hello")
            .thenApply(s -> s + " World")
            .thenAccept(System.out::println)
            .join();

        executor.shutdown();
        executor.awaitTermination(5, TimeUnit.SECONDS);
    }
}

🗣️ Say It Like This in Practice

💬 In an Interview (Explaining Race Condition)
"A race condition is a problem where the result varies depending on execution order when multiple threads access a shared resource at the same time. For example, the counter++ operation consists of three steps, read-modify-write, and if two threads read at the same time, one increment is lost. As a solution, you can use a Lock or use atomic operations such as AtomicInteger. In a previous project, I ran into this problem in the order inventory deduction logic and resolved it with a synchronized block."
💬 In a Meeting (Parallel Processing Strategy)
"The current batch job takes 10 hours, but we can reduce it to 2 hours with parallel processing. We can split the data into 5 chunks by ID range and process them in parallel with ThreadPoolExecutor. However, we need to increase the DB connection pool size from 20 to 50 and check the transaction isolation level. We'll start with 16 threads, which is twice the number of CPU cores, and adjust while monitoring."
💬 In a code review
"In this code, a HashMap is shared by multiple threads, but HashMap is not thread-safe. You should replace it with ConcurrentHashMap or wrap it with Collections.synchronizedMap(). Also, you're creating threads with new Thread() every time, but reusing them with ThreadPoolExecutor can reduce overhead."

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

⚠️ Common Mistakes & Cautions

🔒
Deadlock

Two threads block forever, each waiting for the other's lock. Keep the lock acquisition order consistent, or set a timeout with tryLock(). Use deadlock detection tools (JConsole, VisualVM).

🏃
Race Condition

Missing synchronization when accessing shared variables causes data inconsistency. Use Lock for all shared resource access, and where possible use immutable objects or thread-local variables.

🐍
Python GIL (Global Interpreter Lock)

CPython executes only one thread of Python bytecode at a time. Use the multiprocessing module for CPU-bound tasks, and threading or asyncio for I/O-bound tasks.

✅
The right approach

Reuse threads with a thread pool, minimize shared state, prefer immutable objects, and use thread-safe data structures from the concurrent package. Consider async/await or the actor model where possible.

🔗 Related Terms

📚 Learn More