Skip to content

Instantly share code, notes, and snippets.

Created July 1, 2015 03:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save anonymous/e71364452282bafcf3df to your computer and use it in GitHub Desktop.
Save anonymous/e71364452282bafcf3df to your computer and use it in GitHub Desktop.
package foo;
import co.paralleluniverse.fibers.Fiber;
import co.paralleluniverse.fibers.SuspendExecution;
import co.paralleluniverse.strands.SuspendableRunnable;
import co.paralleluniverse.strands.channels.Channel;
import co.paralleluniverse.strands.channels.Channels;
import co.paralleluniverse.strands.channels.LongChannel;
public class quasarwhispers {
static void quasarWhispers(int n) {
class Whisperer implements SuspendableRunnable {
private LongChannel left, right;
public Whisperer(LongChannel left, LongChannel right) {
this.left = left;
this.right = right;
}
@Override
public void run() throws SuspendExecution, InterruptedException {
try {
long val = left.receive();
right.send(val + 1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
final LongChannel leftmost = Channels.newLongChannel(0);
LongChannel left = leftmost;
LongChannel right = leftmost;
for (long i = 0; i < n; i++) {
right = Channels.newLongChannel(0);
new Fiber<Void>(new Whisperer(left, right)).start();
left = right;
}
new Fiber<Void>(() -> {
try {
leftmost.send(1L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
try {
System.out.println(right.receive());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (SuspendExecution suspendExecution) {
suspendExecution.printStackTrace();
}
}
static void exec() {
for (int i = 0; i < 20; i++)
quasarWhispers(1000000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment