Threads and channels

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
User avatar
jordan4ibanez
Prole
Posts: 14
Joined: Sun Dec 30, 2012 7:22 pm

Threads and channels

Post by jordan4ibanez » Wed Jul 12, 2017 7:35 am

I saw there were no examples linked on the wiki about threads and channels, so I created this visual example of what's going on when passing information into the thread through the channel for people new to threads to utilize.

main.lua

Code: Select all

-- main

--here we create a thread using "print.lua"
thread = love.thread.newThread("print.lua")

--starting a new channel called "channel"
channel = love.thread.getChannel("create")

--starting the thread
thread:start()

--a variable to count
x = 1


while x < 100 do

	x = x + 1
	
	--here we are pushing to the channel, which the thread will recieve
	channel:push({x,x+1,x+2,x+3,x+4})
	
end


--show how long the delay is from when the main program finishes
--to where the thread catches up
while thread:isRunning( ) == true do
	love.timer.sleep(0.1)
	print("print.lua is still running")
end


--shows when all threads are closed
print("print.lua is no longer running")

love.event.quit( )
print.lua

Code: Select all

--print.lua
--here we get the channel that has already been created
channel = love.thread.getChannel("create")

--a random  variable to repeat
repeatr = true

while repeatr == true do
	--when queue count is depleted, break loop
	if channel:getCount( ) == 0 then
		repeatr = false
		break
	end
	--here we recieve the variables from main.lua
	local x = channel:pop()
	
	--creating a string to display the table being sent
	local str = ""
	for i = 1,table.getn(x) do
		str = str..tostring(x[i]).."|"
	end
	
	--printing the string
	print(str.."\n")
	
	--printing the queues remaining
	print("queues:"..channel:getCount( ).."\n")
	--channel:clear()
end

--the end of the print thread
print("end of print.lua")



User avatar
zorg
Party member
Posts: 2745
Joined: Thu Dec 13, 2012 2:55 pm
Location: Absurdistan, Hungary
Contact:

Re: Threads and channels

Post by zorg » Wed Jul 12, 2017 7:38 am

Code: Select all

-- main
thread = love.thread.newThread("print.lua")
channel = love.thread.newChannel()
thread:start(channel)
channel:push("test")

--print.lua
require(love.timer)
channel = ...

while true do
	local x = channel:pop()
	if x then print(x) end
	love.timer.sleep(0.001)
end
Me and my stuff :3True Neutral Aspirant. Why, yes, i do indeed enjoy sarcastically correcting others when they make the most blatant of spelling mistakes. No bullying or trolling the innocent tho.

Post Reply

Who is online

Users browsing this forum: Bing [Bot], Google [Bot] and 15 guests