What are threads?
The flow of actually executing code within a process
The articles written on this blog were created with the goal of teaching. Also, the information in the article may be incorrect, so please be careful.
If a Process is a container that holds resources such as memory and files, a Thread is the flow that actually executes commands within it.
When a process is created, one main thread is usually started, and additional threads can be created if necessary.
Threads in the same process share resources
Threads belonging to the same process share code, global data, heap, and open files. Instead, each thread has its own stack, register state, and execution location.
one process
┌──────────────────────────┐
│ Code / Data / Heap Sharing │
├────────────┬─────────────┤
│ Thread A │ Thread B │
│ Stack A │ Stack B │
│ Register A │ Register B │
└────────────┴─────────────┘
The reason two threads can use the address of the same object is because they share the heap. On the other hand, local variables of functions are basically created on the stack of each thread, so they are separated from each other.
Why use threads?
For example, in a game, a worker thread can do path navigation or resource loading while the main thread handles input and screen updates. If you have multiple CPU cores, different threads may actually run simultaneously.
std::thread worker([]()
{
LoadResources();
});
UpdateGame();
worker.join();
join()causes the current thread to wait until the worker thread finishes.
Difference Between Process and Thread
Processes are basically isolated in memory, so it is difficult for problems in one process to spread directly to other processes. However, the generation and communication costs are relatively large.
Since threads share the same memory, it is easy to exchange data and is relatively lightweight. Instead, incorrect pointer access or synchronization bugs can destroy the entire same process.
Process: Unit of resource ownership and isolation
Thread: Unit of flow executed by CPU
Having more threads doesn't necessarily make things faster. If the cost of dividing tasks, waiting for locks, cache conflicts, and context switching exceeds the computational benefit, it can actually slow down.