Atomicity

Atomicity - Example of Mutex Locks int main(){ pthread_t...

Info iconThis 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”
Background image of page 1

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

View Full DocumentRight 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
Background 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
Background image of page 3

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

View Full DocumentRight Arrow Icon
Background image of page 4
Background image of page 5

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

View Full DocumentRight Arrow Icon
Background 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

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 / 6

Atomicity - Example of Mutex Locks int main(){ pthread_t...

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

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