notes11 - Counter example (renew) Two threads increase a...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
(renew) Two threads increase a counter simultaneiously and some of the increments are lost. Solution: Use mutex locks to enforce the code that increments to be atomic. #include <pthread.h> int main() { int n = 1000000; int count = 0; thread_t t1, t2; mutex_init(&mutex,0); pthread_create(&t1, increment, n/2); pthread_create(&t2, increment, n/2); pthread_join(&t1); pthread_join(&t2); printf(“count = %d\n”, count); } void increment(int n) { for(int i=0; i < n; i++) { mutex_lock(&mutex); // Atomic section; only 1 thread can be here. a) int tmp = count; b) tmp += 1; c) count = tmp; mutex_unlock(&mutex); } } T1 Count = 100 mutex_lock T1: a) tmp = count(100) // context switch; T2 waits T1: b) T1: c) mutex_unlock // context switch; T2 presumes execution T2: a) T2: b) T2: c) If the atomic section (critical section) takes a long time to execute (ex. 1 min), it will prevent other threads from running that section of code. This is critical in multiprocessor computers, because multiple threads that need to execute the critical section will need to stop when thread is in the atomic (or critical) section, making the CPU usage decrease. Conclusion: Keep critical sections as small as possible. After a thread (like T1) calls mutex_unlock(), it is up to the OS to switch to a different thread or it can continue with the same thread. T1: mutex_lock; a; mutex_lock; b; c; mutex_unlock; a; b; c; a; b; mutex_lock; c;
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 01/30/2012 for the course CS 354 taught by Professor Staff during the Fall '08 term at Purdue.

Page1 / 7

notes11 - Counter example (renew) Two threads increase a...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online