遺忘多年的OS...撿回來再這里總結一下。
- Thread vs Process
Both processes and threads are independent sequences of execution. The typical difference is that threads (of the same process) run in a shared memory space, while processes run in separate memory spaces. 一個program至少有一個process,一個process至少有一個thread。When a process terminates,all threads within terminates.
一個process,獨占一個virtual address space(stack, heap, data, text, 4kb or 32bit, 8kb for 64bit)。一個process可以含有多個thread,這些thread共享此virtual address space。
32bit windows,一個process可以用4GB的virtual address space,其中2GB給process,另外兩GB給system。
具體一點,thread share process Code, Data, Heap。但thread has it's own Stack/Program counter/Registers。
In c,fork(), exce(), are for create and execute process. pthread_create(), pthread_join(), are for create thread
- Mutex vs Semaphore
Metaphorly speaking,A mutex is a key to the room (critical sections to avoid race conditions). Only one process or thread is allowed to enter it, and after it's done, it gives key to the next process or thread scheduled.
A Semaphore is a room (critical sections) that can contain N people. It has a counter to notify how many processes or threads can be allowed to use the code simultaneously.
Binary Semaphore is mutex locks, which provides mutual exclusion. Semaphore also can provide orderly based synchronization.
- Starvation vs Deadlock
Starvation happens when ONE process/thread is perpetually denied for resources. For example, if scheduler schedules high priority processes first, and high priority processes are keep coming (If printer prints shorter files first, and people keep giving short files, than longer files may never gets printed).
If TWO or more process in the set is waiting for an event/resources by another process in the set, it's Deaklock. For example, if P1 needs a resource R1 from P2, and P2 needs another resource R2 from P1. Also, in consumer producer example, if there is only one consumer, and only one producer, and both of them sleeps.
Deadlock has four criteria: mutual-exclusion, hold-and-wait, no pre-preemption, circular wait.
Deadlock means it's waiting (not busy-waiting type). But, a busy-waiting process can get Starvation.
- Virtual Memory vs Physical Memory
Physical Memory is RAM size(4GB). Virtual Memory is the storage a program can have. Virtual Memory is on secondary storage (disk).
例如一個32位的CPU,它的地址范圍是0~0xFFFFFFFF (4G),而對于一個64位的CPU,它的地址范圍為0~0xFFFFFFFFFFFFFFFF (64T). 比如對一個16MB的程序和一個內存只有4MB的機器,操作系統通過選擇,可以決定各個時刻將哪4M的內容保留在內存中,并在需要時在內存和磁盤間交換程序片段,這樣就可以把這個16M的程序運行在一個只具有4M內存機器上了。
Semaphore code:
Semaphore本身是struct,value就是number of concurrent threads。List就是一個wait list。(如果value小于0,means how many threads are waiting in queue)
typedef struct {
int value;
struct process *list;
} semaphore;
Wait And Signal
wait(semaphore *S) {
S->value--;
if (S->value < 0) {
add this process to S->list;
block();
}
}
signal(semaphore *S) {
S->value++;
if (S->value <= 0) {
remove a process P from S->list;
wakeup(P);
}
}