Synchronization Problems with Multiple Threads

Synchronization Problems with Multiple Threads -...

Info icon This 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.
Image of page 1

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

View Full Document Right 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; } }
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);
Image of page 3

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

View Full Document Right 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.
Image of page 4
Image of page 5
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern