Thread
Thread
A unit of execution within a process. Can communicate by sharing memory. The basic unit of concurrent programming.
Thread
A unit of execution within a process. Can communicate by sharing memory. The basic unit of concurrent programming.
A thread is the smallest unit of execution within a process. A single process can have multiple threads, and threads within the same process share memory space (heap and data areas). Each thread has its own independent stack and registers, which makes parallel execution possible.
The main advantages of multithreading are improved CPU utilization and better responsiveness. While one thread waits on I/O operations, other threads can use the CPU, and separating the UI thread from worker threads makes it possible to build responsive applications. On multicore processors, performance improves through true parallel processing.
Memory sharing between threads is a double-edged sword. It enables efficient data exchange, but concurrent access creates the risk of race conditions and data corruption. To prevent this, synchronization mechanisms such as mutexes, semaphores, and locks are used.
In modern programming, thread pools or high-level abstractions are used rather than managing threads directly. Examples include Java's ExecutorService, Python's ThreadPoolExecutor, and Go's goroutines and channels. These abstractions reduce the cost of thread creation/destruction and support safe concurrent programming.
// 다양한 언어의 스레드 예제
// Python - threading 모듈
import threading
import time
def worker(name):
print(f"스레드 {name} 시작")
time.sleep(2)
print(f"스레드 {name} 완료")
# 스레드 생성 및 실행
threads = []
for i in range(3):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
# 모든 스레드 완료 대기
for t in threads:
t.join()
print("모든 작업 완료")
// JavaScript - Web Workers (별도 파일)
// worker.js
self.onmessage = function(e) {
const result = heavyComputation(e.data);
self.postMessage(result);
};
// main.js
const worker = new Worker('worker.js');
worker.postMessage(data);
worker.onmessage = (e) => console.log('결과:', e.data);
// Rust - std::thread
use std::thread;
use std::time::Duration;
fn main() {
let handle = thread::spawn(|| {
for i in 1..5 {
println!("스레드에서: {}", i);
thread::sleep(Duration::from_millis(100));
}
});
handle.join().unwrap(); // 스레드 완료 대기
}
Backend developer: "API responses are getting slow because of large file processing. Timeouts happen often."
Tech lead: "How about separating file processing into a separate thread or worker? The request responds immediately, and the processing result is reported asynchronously."
Backend developer: "It would be good to use a thread pool to limit the number of concurrent tasks."
Tech lead: "Yes, and please also build an API that lets us query the processing status."
Interviewer: "Please explain the difference between a thread and a process."
Candidate: "A process is an execution unit with its own independent memory space, and a thread is an execution unit that shares memory within a process. Threads have a lower creation cost and faster communication, but synchronization problems can occur."
Interviewer: "In what situations does a deadlock occur?"
Candidate: "It is a situation where two or more threads wait indefinitely for locks held by each other. It can be prevented by acquiring locks in a consistent order or by setting a timeout."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Reviewer: "Multiple threads are accessing this shared variable at the same time, but there is no synchronization."
Author: "I thought it would be fine because it's just reading. Can it be a problem?"
Reviewer: "If there are no writes, it's mostly fine, but there can be visibility issues. It's safer to use volatile or Atomic types, or to wrap it in a lock."
Author: "Understood. I'll change it to AtomicInteger and also add synchronized blocks where needed."