






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
The concept of synchronization in operating systems, focusing on interleaving threads and processes. Interleaving is possible due to operating system scheduling algorithms, clock interrupts, and I/O interrupts. an example of an unsynchronized threaded program and its incorrect concurrent execution, highlighting the importance of proper synchronization to prevent data inconsistencies.
Typology: Slides
1 / 12
This page cannot be seen from the preview
Don't miss anything!







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:
for (i=0; i<NITERS; i++) cnt++;
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
i (thread) instri %regis 1 cnt
%regis 2
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
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; }
(^) 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