Created
June 18, 2012 22:31
-
-
Save perky/2951177 to your computer and use it in GitHub Desktop.
Blocking threads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--------------------- | |
-- main.lua | |
--------------------- | |
local printerThread | |
local time | |
local function printTextFromPrinterThread() | |
local printText = printerThread:get('print') | |
if printText then | |
print(printText) | |
end | |
end | |
function love.load() | |
printerThread = love.thread.newThread( 'printerThread', 'printer.lua' ) | |
printerThread:start() | |
time = 0 | |
end | |
function love.update( dt ) | |
time = time + dt | |
print('main thread') | |
printTextFromPrinterThread() | |
end | |
function love.draw() | |
local timeLabel = string.format( "%03.2i", time ) | |
love.graphics.print( timeLabel, 10, 10 ) | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--------------------- | |
-- printer.lua | |
--------------------- | |
local printQueue = {} | |
local thisThread = love.thread.getThread() | |
local function print(text) | |
table.insert( printQueue, text ) | |
end | |
local function printSomething() | |
print('printer thread') | |
print('hello') | |
print('world') | |
end | |
local function sendPrints() | |
if #printQueue > 0 and not thisThread:peek('print') then | |
local prints = table.concat( printQueue, "\n" ) | |
thisThread:set('print', prints) | |
printQueue = {} | |
end | |
end | |
while true do | |
printSomething() | |
sendPrints() | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment