Synchronization Problems with Multiple Threads

Synchronization Problems with Multiple Threads -...

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

View Full Document Right Arrow Icon
Synchronization Problems with Multiple Threads Threads share same global variables. Multiple threads can modify the same data structures at the same time This can corrupt the data structures of the program. Even the most simple operations, like increasing a counter, may have problems when running multiple threads.
Background image of page 1

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

View Full DocumentRight Arrow Icon
Example of Problems with Synchronization // Global counter int counter = 0; void increment_loop(int max){ for(int i=0;i<max;i++){ int tmp = counter; tmp=tmp+1; counter=tmp; }
Background image of page 2
Example of Problems with Synchronization int main(){ pthread_t t1,t2; pthread_create(&t1,NULL, increment_loop,10000000); pthread_create(&t2,NULL, increment_loop,10000000); //wait until threads finish pthread_join(&t1); pthread_join(&t2); printf(“counter total=%d”,counter);
Background image of page 3

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

View Full DocumentRight Arrow Icon
Example of Problems with Synchronization We would expect that the final value of counter would be 10,000,000+ 10,000,000= 20,000,000 but very likely the final value will be less than that (E.g. 19,998,045). The context switch from one thread to another may change the sequence of events so the counter may loose some of the counts.
Background image of page 4
Image of page 5
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 252 taught by Professor Gustavorodriguez during the Fall '11 term at Purdue.

Page1 / 7

Synchronization Problems with Multiple Threads -...

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

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