Thread.sleep and resume

Suppose I have some threads:

  • Thread A, which is doing animation and needs to execute every 16msec
  • Thread B, which does some other calculations, and may occasionally block for a long time.
  • Threads B—Z which are running, but never block for more than 5msec.

Suppose that while Thread A is sleeping, Thread B is the current thread. If Thread B knows that it’s taking too long, is there any way to specifically yield time back to Thread A?

Ideas I’ve tried:

  • ThreadB calling sleep(xxx) // although this yields, it may not yield to ThreadA
  • ThreadA calling sleep(16,true) // set wakeEarly=true. This doesn’t really help, as it seems like it just makes ThreadA use 2x or more CPU
  • ThreadB calling ThreadA.resume() // the documentation is unclear but I think that this does not cause a content switch
  • ThreadA.Priority = 100 // setting thread A’s priority really high.

I’ve played with a bunch of settings and I still find that sometimes, ThreadA has 100msec before it wakes up from its 16msec .Sleep() call.

Have you tried increasing thread A’s priority?

I have (it was the 4th item in my list) and it does seem to help.

I’m also seeing something weird. Imagine that ThreadA is sleeping (ThreadA.sleep(16).

  • Calling .sleep(100) inside ThreadB works as expected (ThreadA wakes up every 16msec).
  • However, calling App.SleepCurrentThread(100) inside a timer callback causes ThreadA to repeatedly wake up every millisecond, which seems unexpected and may have been causing anomalies.