I want to know how race condition will happen during context switching, and where and how this happens.
I know about race condition can occur when accessing shared resource, I just need to understand it better. Can someone help me grasp this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Here’s a classic example:
Say the first thread starts running, calls
update(), but gets interrupted (by a signal, context switch, whatever) in-between the second and third instructions. At this stageglobal_int==0andregister==1: it hasn’t saved the result yet.Now suppose a second thread runs
update()and completes, soglobal_int==1. The first thread resumes and savesregister(which is 1) toglobal_int, yielding no change.In this situation,
global_int==1after two calls toupdate()have completed. Anything which assumes thatupdate()updatesglobal_intwill now be broken.In general it is very hard to detect this problem by looking at code, you have to analyse the data and say to yourself “
global_intis being accessed by different threads, I’d better guard it with a mutex”. If you try to get clever and worry about how the threads will access it so as to avoid the expense of a lock, you will probably get it wrong except in trivial cases.