What have you found for these years?

2012-04-04

thread-safe is not fiber-safe; fiber-safe could be even harder (2)

Other posts:
2148. 04-04 thread-safe is not fiber-safe; fiber-safe could be even harder
2149. 04-04 thread-safe is not fiber-safe; fiber-safe could be even harder (2)
2151. 04-05 thread-safe is not fiber-safe; fiber-safe could be even harder (3)

So I just realized that threads are not needed actually. Here's the updated solution:

detect deadlock and retry

require 'fiber'

m = Mutex.new
i = [0]
a = Fiber.new{
      begin
        m.synchronize{ t = i[0]; Fiber.yield; i[0] = t + 1 }
      rescue ThreadError => e
        Fiber.yield e
        retry
      end
    }
b = Fiber.new{
      begin
        m.synchronize{ t = i[0]; Fiber.yield; i[0] = t + 1 }
      rescue ThreadError => e
        Fiber.yield e
        retry
      end
    }
p i # => [0]
while a.alive? || b.alive?
  a.resume if a.alive?
  b.resume if b.alive?
end
p i # => [2]

retry in an eventmachine loop

require 'fiber'
require 'eventmachine'

EM.run{
  m = Mutex.new
  i = [0]
  a = Fiber.new{
        begin
          m.synchronize{ t = i[0]; Fiber.yield; i[0] = t + 1 }
        rescue ThreadError => e
          Fiber.yield e
          retry
        end
      }
  b = Fiber.new{
        begin
          m.synchronize{ t = i[0]; Fiber.yield; i[0] = t + 1 }
        rescue ThreadError => e
          Fiber.yield e
          retry
        end
      }
  p i # => [0]
  EM.add_periodic_timer(0.1){
    if !a.alive? && !b.alive?
      p i # => [2]
      EM.stop
    else
      a.resume if a.alive?
      b.resume if b.alive?
    end
  }
}
Also, I think STM won't really help here, because we need to retry anyway.
The only advantage is that we don't need to "lock" early, but only retry
upon "failures" and yet we would need to define what is a failure.

So in this extremely simple (trivial) example, locking is actually easier than
STM. The advantage of STM, I think, might be the ability to combine and
mix transactions without worrying too much, maybe, I am not sure.
Perhaps if we're using it without too much consideration, we would also
end up with deadlock or livelock, i.e. endless retry.

Next I would try either to implement STM in Ruby to try out, or just try
Haskell next time, given that I'd experience with STM in Haskell.
I need to see how to use coroutines in Haskell though.

0 retries:

Post a Comment

Note: Only a member of this blog may post a comment.



All texts are licensed under CC Attribution 3.0