7 Synchronization
7 Synchronization
Problem
Threads must share data
Data consistency must be maintained
Example
Suppose my wife wants to withdraw $5 from our account and I want to
deposit $10
What should the balance be after the two transactions have been
completed?
What might happen instead if the two transactions were executed
concurrently?
………
if (balance – withdraw >= 0)
balance = balance - withdraw;
else
cout << “not enough money in your account”;
……….
Note that y = y + 1 might be compiled to something like
loadi 2000, R1
load R1, R2
add R2, 1, R2
store R1, R2
• BUSY WAITING
–Software
•Flag
•Alternative
•Peterson
–Hardware
•Disable interrupt
•TSL (Test-and-Set)
while (TRUE) {
while (lock == 1); // wait
lock = 1;
critical-section ();
lock = 0;
noncritical-section ();
}
int turn;
int interested[2]; /* initial FALSE*/
enter_region:
TSL RX, LOCK | copy lock into RX and assign lock = 1
CMP RX, #0 | compare with 0
JNE enter_region | jump if not 0
RET | enter CS
leave_region:
MOVE LOCK, #0 | lock = 0
RET | return
while (TRUE) {
if (busy){
blocked = blocked + 1;
sleep();
}
else busy = 1;
critical-section ();
busy = 0;
if(blocked){
wakeup(process);
blocked = blocked - 1;
}
noncritical-section ();
}
HCMUS 13 CS333: Operating Systems
Semaphore
void Producer(void) {
int item;
while (TRUE) {
item = produce_item();
down(&empty);
down(&mutex);
insert_item(item);
up(&mutex);
up(&full);
}
}
HCMUS 16 CS333: Operating Systems
void Consumer(void) {
int item;
while (TRUE) {
down(&full);
down(&mutex);
item a= remove_item();
up(&mutex);
up(&empty);
consume_item(item);
}
}
void philosopher(int i) // ID
{
while (TRUE) {
think( ); //
take_fork(i); // left fork
take_fork((i+1) % N); // right fork
eat(); //
put_fork(i); //
put_fork((i+1) % N);
}
}
→ If each philosopher keeps one fork
void philosopher(int i) {
while (TRUE) {
think( );
down(mutex);
take_fork(i);
take_fork((i+1) % N);
eat();
put_fork(i);
put_fork((i+1) % N);
up(mutex);
}
}
→ Only one philosopher can eat at a moment
void test(i) {
if (state[i] == HUNGRY &&
state[LEFT] != EATING &&
state[RIGHT] != EATING) {
state[i] = EATING;
up(&s[i]);
}
}