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

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

问题描述

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

When writing multithreaded applications, one of the most common problems experienced is race conditions.

我向社区提出的问题是:

My questions to the community are:

  • 什么是竞争条件?
  • 您如何检测它们?
  • 你如何处理它们?
  • 最后,您如何防止它们发生?

推荐答案

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

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"(例如检查"值是否为 X,然后操作"以执行取决于值为 X 的值)而另一个线程执行某些操作时,通常会出现问题检查"和行为"之间的值.例如:

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天全站免登陆