Docsity

Synchronization in Operating Systems: Interleaving Threads and Processes, Slides of Operating Systems

Partial preview of the text

Download Synchronization in Operating Systems: Interleaving Threads and Processes and more Slides Operating Systems in PDF only on Docsity!

Operating Systems

FALL 2019

Topic#

Synchronization

Interleaving Threads and Processes

Given the (multi-tasking) definition, the context switch between threads/processes is random

This is called interleaving threads or interleaving processes

badcnt.c: An UnSynchronized Threaded Program unsigned int cnt = 0; / shared / #define NITERS 100000000 int main() { pthread_t tid1, tid2; Pthread_create(&tid1, NULL, count, NULL); Pthread_create(&tid2, NULL, count, NULL); Pthread_join(tid1, NULL); Pthread_join(tid2, NULL); if (cnt != (unsigned)NITERS2) printf("BOOM! cnt=%d\n", cnt); else printf("OK cnt=%d\n", cnt); } / thread routine */ void count(void arg) { int i; for (i=0; i<NITERS; i++) cnt++; return NULL; } linux> ./badcnt BOOM! cnt= linux> ./badcnt BOOM! cnt= linux> ./badcnt BOOM! cnt= cnt should be equal to 200,000,000. What went wrong?!

Assembly Code for Counter Loop .L9: movl -4(%ebp),%eax cmpl $99999999,%eax jle .L jmp .L .L12: movl cnt,%regis # Load leal 1(%regis),%regis # Update movl %regis,cnt # Store .L11: movl -4(%ebp),%eax leal 1(%eax),%edx movl %edx,-4(%ebp) jmp .L .L10:

Corresponding asm code

( gcc -O0 -fforce-mem )

for (i=0; i<NITERS; i++) cnt++;

C code for counter loop

Head (Hi)

Tail (Ti)

Load cnt (Li)

Update cnt (Ui)

Store cnt (Si)

Concurrent Execution (cont)

Incorrect ordering: two threads increment the counter, but the result is 1 instead of 2. L 1 U 1 L 2 S 1

U 2
S 2

i (thread) instri %regis 1 cnt

0

%regis 2

Oops!

Concurrent Execution (cont)  How about this ordering? L 1 L 2 U 2 S 2 U 1 S 1

i (thread) instri %regis 1 %regis 2 cnt

 Represent the situation by creating a separate thread for each

person to do the withdrawals

 have both threads run on the same bank mainframe: int withdraw(account, amount) { int balance = get_balance(account); balance -= amount; put_balance(account, balance); return balance; } int withdraw(account, amount) { int balance = get_balance(account); balance -= amount; put_balance(account, balance); return balance; }

Interleaved schedules

 (^) The problem is that the execution of the two threads can be interleaved, assuming preemptive scheduling: balance = get_balance(account); balance -= amount; balance = get_balance(account); balance -= amount; put_balance(account, balance); put_balance(account, balance); Execution sequence as seen by CPU context switch context switch