Skip to content

Instantly share code, notes, and snippets.

@botic
Last active December 31, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save botic/7996577 to your computer and use it in GitHub Desktop.
Save botic/7996577 to your computer and use it in GitHub Desktop.
Force a deadlock in JS – Disclaimer: The programming model of Ringo prevents this situations! This is an extreme example just to show that Ringo is indeed multithreaded JavaScript. In production you avoid this with Workers / queues and don't use shared variables.

Deadlock in bar() looks like:

> ringo deadlock.js 
thread: true
thread: false

Deadlock in foo() looks like:

> ringo deadlock.js 
bar() returned true
thread: true
thread: false
thread: true
thread: false
Loop finished
Counter:10000000
/***** DISCLAIMER *****/
/* This is just a demo that JS is really multithreaded in Ringo and you should never write code like this. */
/***** !!!!!!!!!! *****/
// bar() might return if we are lucky
var bar = function() {
var x = true;
// "inline" thread to change x to false
(new java.lang.Thread({
run: function() {
java.lang.System.out.println("thread: " + x);
x = false;
java.lang.System.out.println("thread: " + x);
}
})).start();
// x might be false, but not for sure because we don't
// know if the inline thread got some CPU time
if (x === false) {
while(true) { /* do nothing --> perfect infinite loop */ }
}
return x;
};
// Its nearly impossible for foo() to return
var foo = function() {
var x = true;
// "inline" thread to change x to false
(new java.lang.Thread({
run: function() {
java.lang.System.out.println("thread: " + x);
x = false;
java.lang.System.out.println("thread: " + x);
}
})).start();
// to give the "bad" thread some CPU time to change the value of x
var z = 0;
for (var i = 0; i < 100000; i++) {
z += Math.random();
}
print("Loop finished");
var counter = 0;
// wait for x to be true --> this is like a
// barrier in front of the return statement
while (x === false) {
counter ++;
if (counter % 10000000 == 0) {
print("Counter:" + counter); // for some visible output
}
}
// We should never reach the return statement
// even if we never change the value of x inside the normal
// function foo, just in the "inline" thread
return x;
};
// Call bar and foo and print returned x
print("bar() returned " + bar());
print("foo() returned " + foo());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment