Created
April 14, 2015 06:10
-
-
Save kasperl/d70d5d63291d22de3d43 to your computer and use it in GitHub Desktop.
Simple message box implementation on top of Fletch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example of a simple message box. | |
import 'dart:collection'; | |
class MessageBox { | |
final Port _port; | |
MessageBox.fromPort(this._port); | |
Port get port => _port; | |
factory MessageBox() { | |
Channel channel = new Channel(); | |
Process.spawn(_serve, new Port(channel)); | |
return new MessageBox.fromPort(channel.receive()); | |
} | |
void send(message) { | |
_port.sendMultiple([_SEND, message]); | |
} | |
receive() { | |
Channel channel = new Channel(); | |
_port.sendMultiple([_RECEIVE, new Port(channel)]); | |
return channel.receive(); | |
} | |
static const int _SEND = 0; | |
static const int _RECEIVE = 1; | |
static void _serve(Port port) { | |
Queue receivers = new Queue(); | |
Queue messages = new Queue(); | |
Channel channel = new Channel(); | |
port.send(new Port(channel)); | |
while (true) { | |
List command = channel.receive(); | |
var operation = command[0]; | |
if (operation == _SEND) { | |
var message = command[1]; | |
if (receivers.isEmpty) { | |
messages.add(message); | |
} else { | |
receivers.removeFirst().send(message); | |
} | |
} else if (operation == _RECEIVE) { | |
var receiver = command[1]; | |
if (messages.isEmpty) { | |
receivers.add(receiver); | |
} else { | |
receiver.send(messages.removeFirst()); | |
} | |
} | |
} | |
} | |
} | |
void producer(port) { | |
MessageBox box = new MessageBox.fromPort(port); | |
for (int i = 0; i < 25; i++) box.send(i); | |
} | |
void consumer0(port) { | |
MessageBox box = new MessageBox.fromPort(port); | |
while (true) { | |
int value = box.receive(); | |
print('0: $value'); | |
} | |
} | |
void consumer1(port) { | |
MessageBox box = new MessageBox.fromPort(port); | |
while (true) { | |
int value = box.receive(); | |
print('1: $value'); | |
} | |
} | |
main() { | |
var box = new MessageBox(); | |
Process.spawn(producer, box.port); | |
Process.spawn(consumer0, box.port); | |
Process.spawn(consumer1, box.port); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment