我已经用多种语言编程,但是我不知道自己的代码中是否存在死锁。
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.
防御死锁:
更多推荐
编程中发生死锁问题的频率有多高?
发布评论