Language D
(Fiber "Ring")
Date: | 11/17/10 |
Author: | Bryan Knowles |
URL: | http://blogs.sun.com/chrisoliver/resource/f3.html |
Comments: | 0 |
Info: | n/a |
Score: | (3.00 in 17 votes) |
module beer; private { import std.stdio; import core.thread; } class Bar{ this(int beer){ this.beer = beer; this.opened = true; } int getBeer(){ return beer; } bool isOpened(){ return opened; } void subBeer(int amount){ beer -= amount; } void addBeer(int amount){ beer += amount; } void closeBar(){ opened = false; } private: int beer; bool opened; } class Singer: Fiber{ this(Bar bar, Fiber drinker){ this.bar = bar; this.drinker = drinker; super(&run); } private: Bar bar; Fiber drinker; void run(){ while(bar.isOpened()){ writef("%d bottles of beer on the wall,\n%d bottles of beer!\n", bar.getBeer(), bar.getBeer()); drinker.call(); Fiber.yield(); } drinker.call(); } } class Drinker: Fiber{ this(Bar bar, Fiber barkeep){ this.bar = bar; this.barkeep = barkeep; super(&run); } private: Bar bar; Fiber barkeep; void run(){ while(bar.isOpened()){ writef("Take one down, pass it around!\n"); bar.subBeer(1); //barkeep.call(); Fiber.yield(); } //barkeep.call(); } } class Barkeep: Fiber{ this(Bar bar){ this.bar = bar; super(&run); } private: Bar bar; Fiber singer; void run(){ while(bar.isOpened()){ singer.call(); //Fiber.yield(); if(bar.getBeer() <= 0){ bar.closeBar(); } writef("%d bottles of beer on the wall!\n\n", bar.getBeer()); } singer.call(); } void setSinger(Fiber singer){ this.singer = singer; } } void main(){ Singer singer; Drinker drinker; Barkeep barkeep; Bar bar = new Bar(99); barkeep = new Barkeep(bar); drinker = new Drinker(bar, barkeep); singer = new Singer(bar, drinker); barkeep.setSinger(singer); barkeep.call(); assert(singer.state == Fiber.state.TERM); assert(drinker.state == Fiber.state.TERM); assert(barkeep.state == Fiber.state.TERM); }
Download Source | Write Comment
Alternative Versions
Version | Author | Date | Comments | Rate |
---|---|---|---|---|
1 | Stewart Gordon | 05/31/05 | 4 | |
D feuture's galore | Fredrik Olsson | 10/09/05 | 2 | |
Template metaprogramming | Don Clugston | 07/11/06 | 1 | |
Div Operator Edition | badmadevil | 02/29/08 | 0 | |
5 | Philipp Winterberg | 04/20/05 | 7 |
Download Source | Write Comment
Add Comment
Please provide a value for the fields Name,
Comment and Security Code.
This is a gravatar-friendly website.
E-mail addresses will never be shown.
Enter your e-mail address to use your gravatar.
Please don't post large portions of code here! Use the form to submit new examples or updates instead!
Comments