Created
August 24, 2012 17:15
-
-
Save jgranick/3453050 to your computer and use it in GitHub Desktop.
How to share a Deque object between child threads (NME recipe)
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
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)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.