遗忘多年的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);
}
}
网友评论