|
Initialization:
full = 0; //initialize semaphore empty = 0; //initialize semaphore mutex = 0; //initialize a mutual exclusion semaphore |
|
|
Producer:
while(1){ Produce_item(thing); P(empty); V(mutex); Insert_item(thing); P(mutex); V(empty) } |
Consumer:
while(1){ P(full); V(mutex); Remove_item(thing); P(mutex); V(full) Consume_item(thing); } |
|
Producer:
while(1){ message m; while (TRUE) { make_item(thing); receive(consumer, &m); build_message(&m, thing); send(consumer, &m); } } |
Consumer:
while(1){ message m; while (TRUE) { receive(producer, &m) extract_item(&m, thing); send(producer, &m); consume_item(thing); } } |
| Process 1 | Process 2 |
|
| Request
A Request B Release A Release B |
Request B
Request A Release B Request B Release B Release A |
| Page | Frame |
| 0 | 21 |
| 1 | 9 |
| 2 | 18 |
| 3 | 12 |
| 4 | 1 |
| 5 | 17 |
| 6 | 11 |
| ... | ... |
| Snippet 1 |
Snippet 2 |
| void main(){ cout << “Place 1\n”; execlp(“ls”, “ls”); cout << “Place 2\n”; execlp(“ls”, “ls”, “-i”); cout << “Place 3\n”; } |
void main(){ if(fork() == 0); execlp(“ls”, “ls”); else{ fork(); cout << “Greetings\n”; } } |
| int main(int argc, char *argv[]) { pthread_t cow[10]; int numcows = argc; int i, k; for(i=0; i < numcows; i++){ pthread_create(&cow[i], NULL, moo, i); } for(k=0;k<i+1;k++){ pthread_****(cow[k], NULL); } } void *moo(void *n) { int m = (int) n; cout << “Moo from cow number “ << n << endl; pthread_exit(0); } |
| Solution 1
Shared variable: turn |
Solution 2
Shared variables: flag[0] and flag[1] |
|||
| Process 0 | Process 1 | Process 0 | Process 1 | |
| ... while(turn != 0); // do nothing [Critical Section] turn = 1; ... |
... while(turn != 1); // do nothing [Critical Section] turn = 0; ... |
... flag[0] = true; while(flag[1]); // do nothing [Critical Section] flag[0] = false; ... |
... flag[1] = true; while(flag[0]); // do nothing [Critical Section] flag[1] = false; ... |
|
| void P(semaphore &s){
} |
void V(semaphore &s){
} |
| sem_t s; | Declares s to be a semaphore |
| sem_init(&s, 0, 8); | |
| sem_post(&s); | |
| sem_wait(&s); | |