Skip to content

Instantly share code, notes, and snippets.

@bil-bas
Created June 11, 2011 10:31
Show Gist options
  • Save bil-bas/1020446 to your computer and use it in GitHub Desktop.
Save bil-bas/1020446 to your computer and use it in GitHub Desktop.
Gosu/fibers minimal fail
# True fibers. WORKS!
require 'fiber'
class Fibers
def initialize
@fiber = Fiber.new do
10.times do
puts "hello"
Fiber.yield
end
end
end
def update
if @fiber.alive?
@fiber.resume
puts "bye"
end
end
end
w = Fibers.new
10.times do
w.update
sleep 0.01
end
# Gosu using true fibers. FAILS!
require 'gosu'
require 'fiber'
class Window < Gosu::Window
def initialize
super(200, 200, false)
@fiber = Fiber.new do
10.times do
puts "hello"
Fiber.yield
end
end
end
def update
if @fiber.alive?
@fiber.resume
puts "bye"
end
end
end
Window.new.show
# Gosu using threads acting like fibers. FAILS!
require 'gosu'
require 'thread'
Thread.abort_on_exception
class Window < Gosu::Window
def initialize
super(200, 200, false)
@mutex = Mutex.new
@cv = ConditionVariable.new
@thread = Thread.new do
10.times do
Thread.stop
@mutex.synchronize do
p Gosu::milliseconds
@cv.signal
end
end
end
Thread.pass
end
def update
if @thread.alive?
@mutex.synchronize do
@thread.run
@cv.wait(@mutex)
p "hello"
end
else
close
end
end
end
Window.new.show
# Using threads acting like fibers (outside Gosu) - WORKS!
require 'thread'
Thread.abort_on_exception
class FakeFibers
def initialize
@cv = ConditionVariable.new
@mutex = Mutex.new
@thread = Thread.new do
p "Started"
10.times do
Thread.stop
@mutex.synchronize do
p Gosu::milliseconds
@cv.signal
end
end
end
Thread.pass
end
def update
if @thread.status
@thread.wakeup
@mutex.synchronize do
@cv.wait(@mutex)
p "hello"
end
end
end
end
w = FakeFibers.new
20.times do
w.update
sleep 0.01
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment