Race conditions

http://stackoverflow.com/questions/34510/what-is-a-race-condition

When writing multi-threaded applications, one of the most common problems experienced are race conditions. My question to the community, is: What is a race condition? How do you detect them? How do you handle them? And finally, how do you prevent them from occurring?


A race condition occurs when 2 or more threads are able to access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any point, you don't know the order at which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are 'racing' to access/change the data.

Often problems occur when one thread does a "check-then-act" (e.g. "check" if the value is X, and then "act" to do something that depends on the value being X) and another thread does something to the value in between the "check" and the "act".

if(x == 5) //The 'Check'
{
   y = x * 2; //The 'Act'
  //If x is changed by another thread in between the if(x==5) and the "y=x*5", y will not be equal to 10.
}

The point being, y could be 10, or it could be anything, depending on whether another thread changed x in between the check and act. You have no real way of knowing.

In order to prevent race conditions occuring, typically you would put a lock around the shared data to ensure that only one thread can access the data at a time. This would mean something like this:

//Obtain lock for x
if(x == 5)
{
   y = x * 2; //Now, nothing can change x until the lock is released. Therefore y = 10
}
//release lock for x


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值