编程中发生死锁问题的频率有多高? [英] How commonly do deadlock issues occur in programming?

查看:81
本文介绍了编程中发生死锁问题的频率有多高?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用多种语言编程,但是我不知道自己的代码中是否存在死锁。

I've programmed in a number of languages, but I am not aware of deadlocks in my code.

我认为这不会发生。

这种情况是否经常发生(在编程中,不是在数据库中),足以引起我的关注?

Does this happen frequently (in programming, not in the databases) enough that I should be concerned about it?

推荐答案

如果满足两个条件,则可能会出现死锁:您有无用的thead,并且它们争用多个资源。

Deadlocks could arise if two conditions are true: you have mutilple theads, and they contend for more than one resource.

您是否编写多线程代码?您可以通过启动自己的线程来显式地执行此操作,或者可以在看不见创建线程的框架中工作,因此您在多个线程中运行而在代码中看不到它。

Do you write multi-threaded code? You might do this explicitly by starting your own threads, or you might work in a framework where the threads are created out of your sight, and so you're running in more than one thread without you seeing that in your code.

一个例子:Java Servlet API。您编写一个servlet或JSP。您部署到应用服务器。有几个用户访问了您的网站,因此也访问了您的servlet。服务器可能每个用户都有一个线程。

An example: the Java Servlet API. You write a servlet or JSP. You deploy to the app server. Several users hit your web site, and hence your servlet. The server will likely have a thread per user.

现在考虑如果在处理请求时想要获取一些资源会发生什么情况:

Now consider what happens if in servicing the requests you want to aquire some resources:

if ( user Is Important ){
     getResourceA();
}

getResourceB();

if (today is Thursday ) {
    getResourceA();
} 


// some more code

releaseResourceA();
releaseResoruceB();

在上面的人为示例中,请考虑当重要用户的请求到达时,星期四会发生什么,

In the contrived example above, think about what might happen on a Thursday when an important user's request arrives, and more or less simultaneously an unimportant user's request arrives.

重要用户的线程获得Resoruce A并想要B。不太重要的用户获得资源B并想要A。释放它们已经拥有的资源...死锁。

The important user's thread gets Resoruce A and wants B. The less important user gets resource B and wants A. Neither will let go of the resource that they already own ... deadlock.

如果您正在编写明确使用同步的代码,则实际上很容易发生。我最常见的情况是使用数据库时会发生这种情况,幸运的是数据库通常具有死锁检测功能,因此我们可以找出发生了什么错误。

This can actually happen quite easily if you are writing code that explicitly uses synchronization. Most commonly I see it happen when using databases, and fortunately databases usually have deadlock detection so we can find out what error we made.

防御死锁:


  1. 以明确的顺序获取资源。在上述示例中,如果总是在资源B之前获得资源A,则不会发生死锁。

  2. 如果可能的话,请使用超时机制,这样您就不必无限期地等待资源了。这将使您能够检测到争用并应用防御1。

这篇关于编程中发生死锁问题的频率有多高?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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