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
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()); |