Skip to content

Instantly share code, notes, and snippets.

@jlnr jlnr/gosu_mt.rb
Last active Jan 16, 2017

Embed
What would you like to do?
Using Gosu asynchronously (experimental) - see https://www.libgosu.org/cgi-bin/mwf/topic_show.pl?tid=1319
#!/usr/bin/env ruby
require "gosu"
class AsyncWindow < Gosu::Window
def initialize(*args)
super
@update_mutex = Mutex.new
@update_cv = ConditionVariable.new
@draw_mutex = Mutex.new
@draw_cv = ConditionVariable.new
end
def needs_redraw?
@draw_mutex.synchronize { @draw_block != nil }
end
def update
@update_mutex.synchronize do
if @update_block
@update_block.call
@update_block = nil
@update_cv.signal
end
end
end
def draw
@draw_mutex.synchronize do
if @draw_block
@draw_block.call
@draw_block = nil
@draw_cv.signal
end
end
end
def schedule_update(&block)
@update_mutex.synchronize do
@update_block = block
@update_cv.wait(@update_mutex)
end
end
def schedule_draw(&block)
@draw_mutex.synchronize do
@draw_block = block
@draw_cv.wait(@draw_mutex)
end
end
end
window = AsyncWindow.new(300, 200)
Thread.new do
loop do
sleep 1
window.schedule_update { window.caption = "Game has been running for #{Gosu.milliseconds}ms" }
# control will only get here after the above block has been run on the main thread
sleep 1
window.schedule_draw { Gosu.draw_rect(0, 0, 300, 200, 0xff_000000 | rand(0x1_000000)) }
# control will only get here after the above block has been run on the main thread
end
end
window.show
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.