Simple examples of blocking
source link: https://www.codesd.com/item/simple-examples-of-blocking.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Simple examples of blocking
I would like to explain threading deadlocks to newbies. I have seen many examples for deadlocks in the past, some using code and some using illustrations (like the famous 4 cars). There are also classic easily-deadlocked problems like The Dining Philosophers, but these may be too complex for a real newbie to fully grasp.
I'm looking for the simplest code example to illustrate what deadlocks are. The example should:
- Relate to a "real" programming scenario that makes some sense
- Be very short, simple and straight forward
What do you recommend?
Maybe a simple bank situation.
class Account {
double balance;
void withdraw(double amount){
balance -= amount;
}
void deposit(double amount){
balance += amount;
}
void transfer(Account from, Account to, double amount){
sync(from);
sync(to);
from.withdraw(amount);
to.deposit(amount);
release(to);
release(from);
}
}
Obviously, should there be two threads which attempt to run transfer(a, b) and transfer(b, a) at the same time, then a deadlock is going to occur because they try to acquire the resources in reverse order.
This code is also great for looking at solutions to the deadlock as well. Hope this helps!
Related Articles
Example of blocks in ios5
ANTLR: Is there a simple example?
Simple example of decoupling the user interface and network calculation
Simple Example Linq Subquery
Simple example of Masstransit with RabbitMQ
Can someone give me a very simple example to change the color of the text?
Simple example using Backbone.js and Rivets.js
& Ldquo; Can not find the symbol & rdquo; Error - even on a ridiculously simple example
American Fuzzy Lop fails with a simple example
NodeJs callback simple example
WPF MVVM EF Simple example
A simple example of Django and CSS
How do I pass a statement by reference in this simple example?
Simple examples implementing push notifications using the latest Phonegap for iOS?
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK