Skip to content
Jason R. Clark edited this page May 14, 2015 · 1 revision

The current default backend for Shoes (shoes-swt) has a restriction that only the main thread can access UI elements. This means that if you wrote this code:

Shoes.app do
  Thread.new do
    10.times do
      para "Threads are awesome"
      sleep 1.1
    end
  end
end

...your app would fail with the dreaded org.eclipse.swt.SWTException: Invalid thread access

Shoes doesn't currently provide any direct solution for this (i.e. a method to call from the background thread to force action on the main thread). However, you can structure your app to avoid the problems by following these principles:

  1. Use data structures like Queue to track the raw information from your thread.
  2. Access Shoes UI from animate blocks on the main thread, reading from the same Queue accessed by the thread.

Here's an example of it in action:

require 'thread'

Shoes.app do
  @paras = Queue.new
  Thread.new do
    10.times do
      @paras.push "Threads are awesome"
      sleep 1.1
    end
  end

  animate do
    until @paras.empty?
      para @paras.pop
    end
  end
end

Note that this example doesn't actually require threads, since animate itself could provide us a timer, but if the work in the thread was more intermittent, or responding to other outside events, this technique might apply.