{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Atomicity - Example of Mutex Locks int main pthread_t t1,t2...

Info icon This preview shows pages 1–6. Sign up to view the full content.

View Full Document Right Arrow Icon
Atomicity Atomic Section: A portion of the code that only one thread should execute at a time while the other threads have to wait. Otherwise corruption of the variables is possible. An atomic section is also called sometimes a “Critical Section”
Image of page 1

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

View Full Document Right Arrow Icon
Mutex Locks Mutex Locks are software mechanisms that enforce atomicity Declaration: #include <pthread.h> pthread_mutex_t mutex; Initialize pthread_mutex_init( &mutex, atttributes); Start Atomic Section pthread_mutex_lock(&mutex); End Atomic section pthread_mutex_unlock(&mutex);
Image of page 2
Example of Mutex Locks #include <pthread.h> int counter = 0; // Global counter pthread_mutex_t mutex; void increment_loop(int max){ for(int i=0;i<max;i++){ pthread_mutex_lock(&mutex); int tmp = counter; tmp=tmp+1; counter=tmp; pthread_mutex_unlock(&mutex); Thread s
Image of page 3

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

View Full Document Right Arrow Icon
Example of Mutex Locks
Image of page 4
Image of page 5

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

View Full Document Right Arrow Icon
Image of page 6
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Example of Mutex Locks int main(){ pthread_t t1,t2; pthread_mutex_init(&mutex,NULL); pthread_create(&t1,NULL, increment,10000000); pthread_create(&t2,NULL, increment,10000000); //wait until threads finish pthread_join(&t1); pthread_join(&t2); Example of Mutex Locks T1 T2 T0 (main) for(…) mutex_lock(&m) a)tmp1=counter (tmp1=0) (Context switch) Join t1 (wait) Starts running mutex_lock(&m) (wait) (context switch) b)tmp1=tmp1+1 c)counter=tmp1 Counter=1 mutex_unlock(&m) a)tmp2=counter b)tmp2=tmp2+1 c)counter=tmp2 time Example of Mutex Locks • As a result, the steps a),b),c) will be atomic so the final counter total will be 10,000,000+ 10,000,000= 20,000,000 no matter if there are context switches in the middle of a)b)c)...
View Full Document

{[ snackBarMessage ]}