해당 노트는 UC Berkeley CS162 lecture 2를 듣고 작성한 강의 노트이다.
Each thread can represent one chunk of code and is a unit of concurrency provided by the OS. In other words, the OS can handle multiple things at once with threads.
A thread is in one of the three states: running, ready and blocked. If a thread is waiting for an I/O to finish, the OS marks it as blocked. Once the I/O operation finishes, the OS marks it as ready. Once a process starts, it issues system calls to create new threads. The calls are usually made by OS library or language runtime so system calls are hidden below programming interface. For example, in C library issues a system call with some special assembly code and then the kernel creates a new thread and return the values and the program runs in user mode again.
Main thread creates, or, forks subthreads and after its subthreads are done, it joins with them, collecting their results. While content of memory and I/O state are shared by all threads in one process, information in TCB, CPU registers(including program counter) and execution stack are kept private to each thread. Execution stack stores parameters and temporary variables. A thread’s stack can touch that of another thread but since the focus of protection is on process itself, not individual threads, procedures to prevent this aren’t essential.
Scheduler can run threads in any order and can switch threads at any time. This can be problematic in race conditions where threads might depend on the result of other threads. To prevent race conditions, synchronization is needed. A lock is an object only one thread can hold at a time, ensuring only one thread does a particular thing at a time. Before a thread executes, it will claim to acquire a lock and after execution it will release the lock so one of the other threads can acquire it.
Processes are always created by other processes and the first process is initiated by the kernel. The OS library calls main thread (i.e. public static void main(String[] args) in java) and when main returns, the library calls exit on the process.