I wanted to make a http request while my game is running, and i tought the threads would be the perfect way to do it. However i found no snippets on the wiki and i found few up-to-date examples (which i tried to use but still can't make it to work). So far i have this 2 files:
function love.load()
http = require("socket.http")
thread = love.thread.newThread("thread.lua")
channel = love.thread.getChannel("test")
thread:start()
i = {}
channel:supply("get")
end
function love.update(dt)
v = ""
v = channel:pop()
print(v)
end
function love.draw()
--love.graphics.print(tostring(i[1]), 10, 10)
end
function love.keypressed(key, isrepeat)
channel:supply("get")
v = ""
v = channel:pop()
print(v)
end
c = love.thread.getChannel("test")
http = require("socket.http")
num = c:pop()
print(num)
if num == "get" then
print("staring")
res = http.request("http://google.com")
--print(res)
c:supply(res)
end
I wanted to test using the love.keypressed to send a http request but only the channel:supply("get") on the love.load works, whenever i press a key the program stops responding. What am i doing wrong? Is there another way to get http requests without freezing my game while waiting for a response?
pop() does not wait, but supply() does wait. I think what's happening is:
1. Your thread starts and does a pop(). Since there's nothing, it returns nil, executes the rest of the code, and the thread terminates.
2. When you press a key, the main application uses supply(), which waits for someone to receive it. But there's no one, because the thread has terminated.
An immediate solution is to use demand() instead of pop() in the thread, which does wait until there's data.
Similarly, use push() rather than supply() in main, so that the main application is not blocked until the thread can attend it.
The Problem is that your thread exits after doing one request, you need an (infinite) loop there.
also it still wouldn't work as expected because as pgimeno pointed out, pop doesn't wait for a value to become available so you might "miss" the result.
Take a look at the wiki and look at the differences between "pop" and "demand" and "push" and "supply".
Thank you... i didnt knew i needed a while loop on the thred file... Thanks a lot! Btw how can i keep track of different responses at the same time? I mean, the result variable will return the latest response.. Any ideas?
"You certainly usually find something, if you look, but it is not always quite the something you were after."
-Thorin Oakenshield, J.R.R. Tolkien