# How do threads decide when to 'go'? [closed]

I have written some code that animates two boxes using HTML5 and JavaScript threads. I set them up to move at a fixed rate, which is the same:

executeEvery(box1.animate(), 10);
executeEvery(box2.animate(), 10);


The result is weird for reasons not important here. This to me seems to be the two executeEvery calls not working in unison - probably some asynchronous issue. Because animate() is a complex function call, the threads behaviour is seemingly erratic.

I am asking here because I think this problem is deeper than a JavaScript issue. Why does this not work as intended?

• Programming questions are offtopic here; I rewrote the question to focus on the core issue. – Raphael Oct 21 '15 at 6:53
• Javascript is single-threaded. And this is offtopic. – KWillets Oct 21 '15 at 8:03
• You need to ask on Stack Overflow. Your question is very strongly dependent on the behavior of execueEvery and animate: it's about Javascript (perhaps even a specific implementation of JS, I don't know how standard this is) and the libraries you're using. The only science answer is that there are many models of concurrency that are very different and explaining all the possibilities would fill a whole book. – Gilles 'SO- stop being evil' Oct 21 '15 at 14:20
• @Gilles I think some basic issues of concurrency are sufficient to answer the basic question here. How do achieve things in JS should go to Stack Overflow. – Raphael Oct 22 '15 at 15:34
• @Raphael Your answer assumes preemptive thread, but AFAIK Javascript doesn't have them, so it's more confusing than anything. – Gilles 'SO- stop being evil' Oct 22 '15 at 15:52

## 1 Answer

There are (at least) four reasons.

1. They do not start at the same time. Before the second executeEvery is even found by the interpreter, the first one may already have executed some steps!

2. You don't even know if the platform supports parallelism. So you can only expect one move to be computed after the other; you may be able to control the relative speed (see below).

3. The threads themselves don't have any control over this (on most machines). Either a virtual or the actual machine runs a scheduler that decides which process or thread runs when. For the programmer, the only robust way to deal with this is by assuming non-determinism (i.e. arbitrary order).

4. wait(10) won't wait for exactly 10ms. Even active waiting can get you only so close to the exact time frame.

If you want to execute the updates simultaneously -- in the sense that both boxes make their $i$th move before they do their respective $(i+1)$th -- you will have to use means of synchronisation, e.g. a barrier.