# Thread hangs when no delay is used

**URL:** <https://discourse.processing.org/t/thread-hangs-when-no-delay-is-used/5352>\
**Category:** Coding Questions\
**Created:** [November 8, 2018, 6:54pm UTC](https://discourse.processing.org/t/thread-hangs-when-no-delay-is-used/5352 "2018-11-08T18:54:04Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![clankill3r](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/clankill3r/32/1098_2.png) [@clankill3r](https://discourse.processing.org/u/clankill3r)\
**Post date:** [November 8, 2018, 6:54pm UTC](https://discourse.processing.org/t/thread-hangs-when-no-delay-is-used/5352/1 "2018-11-08T18:54:04Z")

</div>

When I remove `delay(1)` in the code below then last\_frame will always be equal to frameCount and there is no movement.

Why is that?

```auto
PVector v = new PVector();

void setup() {
  thread("whyOwhy");
}

void whyOwhy() {
  
  int last_frame = 0;  
  
  while (true) {
    if (last_frame != frameCount) {
      v.x += 1;
      last_frame = frameCount;
    }
    delay(1);
  }
}

void draw() {
  background(0);
  fill(255);
  v.y += 0.1;
  fill(255);
  ellipse(v.x, v.y, 10, 10);
}

```

---

<div class="post-metadata">

**Author:** ![neilcsmith](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/neilcsmith/32/144_2.png) [@neilcsmith](https://discourse.processing.org/u/neilcsmith)\
**Post date:** [November 8, 2018, 7:22pm UTC](https://discourse.processing.org/t/thread-hangs-when-no-delay-is-used/5352/2 "2018-11-08T19:22:32Z")

</div>

One reason may be that frameCount isn’t marked volatile so the JVM is quite entitled to read and store the value before entering your while loop.

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [November 8, 2018, 7:24pm UTC](https://discourse.processing.org/t/thread-hangs-when-no-delay-is-used/5352/3 "2018-11-08T19:24:27Z")

</div>

For more Thread stuff, you can read this whole post: 👽

> [@While loop bug? Stuck on empty](https://discourse.processing.org/t/while-loop-bug-stuck-on-empty/2557):
>
> Hi I have a weird bug in a sketch that I’m using to control a plotter. I have a while loop that is controlled by a boolean that is switched to false while the plotter is in the middle of doing something. Once the plotter is finished it sends a serial command to my sketch and flips nextMove=true; This aspect of it is working correctly and I am checking the nextMove variable and it is set to true. The weird part the sketch gets stuck in the loop even though the variable is set to true. If I pu…

---

<div class="post-metadata">

**Author:** ![Lexyth](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/lexyth/32/7403_2.png) [@Lexyth](https://discourse.processing.org/u/Lexyth)\
**Post date:** [November 9, 2018, 9:48am UTC](https://discourse.processing.org/t/thread-hangs-when-no-delay-is-used/5352/4 "2018-11-09T09:48:50Z")

</div>

Well, to sum up what Happens there… :

```auto
if (frameCount != lastFrame) {
  lastFrame = frameCount;
}

```

So, if fC = 23 and LF = 23, then nothing happens, But if fC = 24 and LF = 23, then LF is set to 24. So if you Print LF After that Statement it will always be equal to fC. Because fC is set at the start of a new Frame. Then it’s checked if they‘re equal and so Lc will end up as equal to fC after the statement. But before it should be different by 1, unless it‘s only set every n Frame. Then the difference is n.

---

<div class="post-metadata">

**Author:** ![Jakub](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jakub/32/2192_2.png) [@Jakub](https://discourse.processing.org/u/Jakub)\
**Post date:** [November 9, 2018, 11:01am UTC](https://discourse.processing.org/t/thread-hangs-when-no-delay-is-used/5352/5 "2018-11-09T11:01:53Z")

</div>

I think @neilcsmith is right and `frameCount` is cached before the while loop by the JVM. Compiler is free to do this, because there is no synchronization in your code and the compiler assumes there will be no changes from different threads. Delay causes the thread to sleep which probably - I am guessing - creates a memory barrier and the values changed in other threads get updated in your `whyOwhy` thread as well.

Another problem is that `v.x` is updated in the background thread, but the main thread might not see the changes.

Both of these problems happen because the access to these variables is not synchronized in your sketch.

To make programs behave in a predictable way, you _must_ synchronize all access to data which is touched from multiple threads (except read-only data). A consequence of this is you can’t safely read or write any built-in variables from threads, because PApplet modifies them without synchronization and you can’t fix it from within your sketch. You need to create your own variables which you then make sure are properly synchronized.

---

<div class="post-metadata">

**Author:** ![neilcsmith](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/neilcsmith/32/144_2.png) [@neilcsmith](https://discourse.processing.org/u/neilcsmith)\
**Post date:** [November 9, 2018, 11:50am UTC](https://discourse.processing.org/t/thread-hangs-when-no-delay-is-used/5352/6 "2018-11-09T11:50:15Z")

</div>

> [@Jakub](#):
>
> Delay causes the thread to sleep which probably - I am guessing - creates a memory barrier

That’s definitely one possibility, although if so is going to be implementation / CPU specific - pretty sure it’s not specified to create one.

Of course, another option is that they’re both broken! Just one isn’t given time to show up. Aggressive compilation depends on threshold numbers (1000s) of times through a loop. A hard loop will hit that quickly. Add a sleep in and the compile threshold just might not be being reached in the observed time.

One of the biggest problems I see with multi-threaded examples here that don’t use synchronisation or volatiles is the assumption that because things work for a while they’ll carry on working.

> [@Jakub](#):
>
> Another problem is that `v.x` is updated in the background thread, but the main thread might not see the changes.

Good point! If the only way of observing whether the frameCount value triggers the if clause is this then either or both could be the problem.

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [November 9, 2018, 6:33pm UTC](https://discourse.processing.org/t/thread-hangs-when-no-delay-is-used/5352/7 "2018-11-09T18:33:54Z")

</div>

> [@Jakub](#):
>
> **delay()** causes the Thread to sleep which probably - I am guessing - creates a memory barrier and the values changed in other threads get updated in your **whyOwhy()**'s Thread as well.

IMO, that’s what happens: **delay()** forces an update between the local Thread’s cache & the main memory. 🧵

So there’s no need for any further types of synchronization (even `volatile` fields) if we use **delay()**, in case we just need all local fields to be updated to the main memory. 🐌

A tight loop w/o any **delay()**, besides hammering the CPU super hot nonstop, can make all changes to a field (or an array’s index) to stay stuck in the current Thread’s local cache memory. 🥵

---

<div class="post-metadata">

**Author:** ![neilcsmith](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/neilcsmith/32/144_2.png) [@neilcsmith](https://discourse.processing.org/u/neilcsmith)\
**Post date:** [November 9, 2018, 8:47pm UTC](https://discourse.processing.org/t/thread-hangs-when-no-delay-is-used/5352/8 "2018-11-09T20:47:41Z")

</div>

> [@GoToLoop](#):
>
> So there’s no need for any further types of synchronization (even `volatile` fields) if we use **delay()**

This is just not true. _Please stop giving people stupidly erroneous advice_. There is a Java memory model spec. Follow it or don’t be surprised if at some point something might break.

For further reading, see the second and third paragraph of 17.3 here, which explicitly covers your point - [Chapter&nbsp;17.&nbsp;Threads and Locks](https://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html)

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [November 10, 2018, 1:54am UTC](https://discourse.processing.org/t/thread-hangs-when-no-delay-is-used/5352/9 "2018-11-10T01:54:26Z")

</div>

> [@neilcsmith](#):
>
> … see the second and third paragraph of 17.3 here, …

> … the compiler **does not have to** flush writes cached in registers out to shared memory before a call to `Thread.sleep` or `Thread.yield`, **nor does the compiler have to** reload values cached in registers after a call to `Thread.sleep` or `Thread.yield`.

The main thing is: “does not have to”.  
It means it isn’t obliged to, but still it has permission to do so!

implementors are free to go beyond the minimum specs, as long as the language’s spec doesn’t prohibit it.

And so far, **Thread.sleep()** (**delay()** in Processing) hasn’t failed to flush local cached fields to main memory for every single case where threads are used in Processing.

---

<div class="post-metadata">

**Author:** ![Jakub](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jakub/32/2192_2.png) [@Jakub](https://discourse.processing.org/u/Jakub)\
**Post date:** [November 10, 2018, 8:55am UTC](https://discourse.processing.org/t/thread-hangs-when-no-delay-is-used/5352/10 "2018-11-10T08:55:03Z")

</div>

You can’t make a reliable concurrent program by testing it and saying that it works so the code is right. You have to be able to defend that everything is properly synchronized and accounted for.

That’s the hard part of concurrency in Java: you can’t fiddle around until it seems to work, you have to know that your code is right.

Otherwise you get strange bugs which happen only sometimes, usually during exhibitions or performances. Good luck finding the source of the problem then 😅

---

<div class="post-metadata">

**Author:** ![neilcsmith](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/neilcsmith/32/144_2.png) [@neilcsmith](https://discourse.processing.org/u/neilcsmith)\
**Post date:** [November 10, 2018, 9:44am UTC](https://discourse.processing.org/t/thread-hangs-when-no-delay-is-used/5352/11 "2018-11-10T09:44:50Z")

</div>

> [@GoToLoop](#):
>
> And so far, **Thread.sleep()** ( **delay()** in Processing) hasn’t failed to flush local cached fields to main memory for every single case where threads are used in Processing.

You have absolutely no basis to make that statement! You just haven’t observed it yet. And even if you have something that works despite the spec you can’t guarantee that running it on a different machine or OS or next point release of the JVM won’t break it. I’ve been in enough conference talks and discussions with people involved with HotSpot not to trust a word you say on it!

Jakub’s right, these are often things that don’t show up until long running in performances and exhibitions. Been there, got the T-shirt! 😄 PraxisLIVE actually started out because of this, not as a live programming environment, but as an actor-based architecture I could build projects with using a universal lock-free message passing system - all cross-thread communication routed through one place. Processing could really benefit from a simplified but similar mechanism - threading just confuses beginners (and non-beginners 😜 )

---

<div class="post-metadata">

**Author:** ![clankill3r](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/clankill3r/32/1098_2.png) [@clankill3r](https://discourse.processing.org/u/clankill3r)\
**Post date:** [November 10, 2018, 11:07am UTC](https://discourse.processing.org/t/thread-hangs-when-no-delay-is-used/5352/12 "2018-11-10T11:07:45Z")

</div>

Thanks for all the help.

I have it different know.

I made

`public void set_time_out(int time, Runnable callback) {`

To have things on another thread that don’t draw in the animation thread etc.

And I have the non async `for_n_frames`:

To make a vector move in a square for example I can use:

```auto
int frames = 60;
for_n_frames(frames, ()-> {
            v.x++;
        }, 
        ()-> {
            for_n_frames(frames, ()-> {
                v.y++;
            }, 
            () -> {
                for_n_frames(frames, ()-> {
                    v.x--;
                }, 
                ()-> {
                    for_n_frames(frames, ()-> {
                        v.y--;
                    }, 
                    callback); 
                });
            });
        });

```
