Skip to content

Instantly share code, notes, and snippets.

@jgranick
Created August 24, 2012 17:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgranick/3453050 to your computer and use it in GitHub Desktop.
Save jgranick/3453050 to your computer and use it in GitHub Desktop.
How to share a Deque object between child threads (NME recipe)
import cpp.vm.Deque;
import cpp.vm.Thread;
import cpp.Sys;
import nme.display.Sprite;
import nme.Lib;
class ThreadingExample extends Sprite {
public function new () {
super ();
var data = new Deque <Int> ();
var first = Thread.create (sendData);
var second = Thread.create (receiveData);
first.sendMessage (data);
second.sendMessage (data);
trace ("This message will not wait for the result");
}
private function sendData ():Void {
var data = Thread.readMessage (true);
for (i in 0...10) {
data.push (i);
trace ("Sending data: " + i);
Sys.sleep (0.1);
}
}
private function receiveData ():Void {
var data = Thread.readMessage (true);
for (i in 0...10) {
trace ("Receiving data: " + data.pop (true));
}
}
}
@jgranick
Copy link
Author

The "Sys.sleep" call in the "sendData" method above would not normally be necessary, but it helps when making this sample.

Each thread runs on their own time. On my system, the "sendData" method was able to add around 4 values before the "receiveData" method began popping them.

For sake of a sample, causing the first thread to sleep and making the second thread block when popping values helps them occur in a more exact order.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment