什么是竞争条件? [英] What is a race condition?

查看:893
本文介绍了什么是竞争条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写多线程应用程序时,遇到的最常见问题之一是竞争条件。

When writing multi-threaded applications, one of the most common problems experienced are race conditions.

我向社群提出的问题是:

My questions to the community are:

什么是比赛条件?如何检测它们?你如何处理他们?

What is a race condition? How do you detect them? How do you handle them? Finally, how do you prevent them from occurring?

推荐答案

当两个或多个线程可以访问共享数据时,会发生竞争条件,尝试同时更改它。因为线程调度算法可以随时在线程之间交换,所以您不知道线程尝试访问共享数据的顺序。因此,数据变化的结果取决于线程调度算法,即两个线程都竞争访问/改变数据。

A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in 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.

当一个线程执行check-then-act(例如check如果值为X,然后act值为X),另一个线程对check和act之间的值执行某种操作。例如:

Problems often occur when one thread does a "check-then-act" (e.g. "check" if the value is X, 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". E.g:

if (x == 5) // The "Check"
{
   y = x * 2; // The "Act"

   // If another thread changed x in between "if (x == 5)" and "y = x * 2" above,
   // y will not be equal to 10.
}

点是,y可以是10,它可以是任何东西,这取决于另一个线程是否在检查和行为之间改变x。你没有真正的方式知道。

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 from occurring, you would typically put a lock around the shared data to ensure 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

这篇关于什么是竞争条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆