Dynamic Scope

Get Version

1.0.2

→ ‘contextr

This explanation is a bit tricky. First of all thread programming is always tricky and then, testing threads to gain repeatable results makes it even less readable.

I tried to improve it by defining a little helper method called step. It shall test if all chunks are executed in the expected order and additionally check if the expected layers are activated.

Layer activation shall be dynamically scoped. This is basically no problem, but it gets messy when doing thread programming and switching between scopes. The ugly part is done by Christian Neukirchen’s dynamic.rb library.

The following example does not demonstrate anything useful. It is just a more or less readable test. Follow the steps, if you want to get the execution order. As you may see, leaving the inner block in step 5 results in the “lost” layer :b and it is “restored” in step 6. This is the base line of this test. All the rest is support code.

example do
  def step(index, *layers)
    @step ||= 0
    assert_equal(index, @step += 1) if index
    assert_equal(layers, ContextR::active_layers)
  end

  mutex = Mutex.new

  one_block = lambda do
    mutex.lock
    ContextR::with_layer :b do
      step(3, :b, :a)
      mutex.unlock
      sleep(0.1)
      mutex.lock
      step(5, :b, :a)
    end
  end

  two_block = lambda do
    mutex.lock
    step(4, :a)
    mutex.unlock
  end

  step(1)
  ContextR::with_layer :a do
    step(2, :a)

    one = Thread.new(&one_block) 
    two = Thread.new(&two_block)
    
    step(nil, :a)

    one.join
    two.join

    step(6, :a)
  end
  step(7)
end

28th April 2008
Theme extended from Paul Battley