Quick Links: Download Gideros Studio | Gideros Documentation | Gideros community chat | DONATE
New 'Threads' plugin - how to use it? — Gideros Forum

New 'Threads' plugin - how to use it?

Apollo14Apollo14 Member
edited October 2018 in Code snippets
Hi guys!
I don't get why value of 'a' isn't changed in the end?
require "Threads"
local thread = Thread.new()
 
local a=1
 
thread:setFunction(function()
	for i=1, 1000000 do
		a=a+1
	end
end)
 
thread:execute()
 
local timerDelayed = Timer.delayedCall(2000, function()
	print("a=",a) --prints a=1, though I expected a=1000000
end)
Thx!

p.s. and how to properly pass args?
require "Threads"
local thread = Thread.new()
 
local a=1
 
thread:setFunction(function(arg)
	print(arg) --nothing prints, whole function isn't executed
	for i=1, 1000000 do
		a=a+1
	end
end)
 
thread:execute("test arg")
> Newcomers roadmap: from where to start learning Gideros
"What one programmer can do in one month, two programmers can do in two months." - Fred Brooks
“The more you do coding stuff, the better you get at it.” - Aristotle (322 BC)

Comments

  • SinisterSoftSinisterSoft Maintainer
    Accepted Answer
    The thread is a different instance of Lua - so imagine you are programming a new instance and running it with:
    for i=1, 1000000 do
    	a=a+1
    end
    passing 'a' to and from the new instance is best answered by @PaulR :)
    Coder, video game industry veteran (since the '80s, ❤'s assembler), arrested - never convicted hacker (in the '90s), dad of five, he/him (if that even matters!).
    https://deluxepixel.com
  • okay this code seems to be working now, thx @SinisterSoft !
    require "Threads"
    local thread = Thread.new()
     
    thread:setFunction(function(arg)
    	local passedArg=arg
    	local a=1
    	for i=1, 1000000 do
    		a=a+1
    	end
    	return a, passedArg
    end)
     
    thread:execute("passed arg string")
     
    local timerDelayed = Timer.delayedCall(2000, function()
    	local status,a,arg=thread:getResult()
    	print(status) --prints 'true'
    	print(a) --prints '1000001'
    	print(arg) --prints 'passed arg string'
    end)

    Likes: SinisterSoft

    > Newcomers roadmap: from where to start learning Gideros
    "What one programmer can do in one month, two programmers can do in two months." - Fred Brooks
    “The more you do coding stuff, the better you get at it.” - Aristotle (322 BC)
    +1 -1 (+1 / -0 )Share on Facebook
  • PaulRPaulR Member, Maintainer
    Yes, that's it. You can also yield from the thread and resume operation from the main thread state. I'm currently updating it, there's a couple of bugs too (like not being able to pass nil values) that have also been fixed. I'll write a tutorial on it soon!
    +1 -1 (+4 / -0 )Share on Facebook
  • @PaulR, really exciting, thanks for your work.

    Likes: PaulR

    +1 -1 (+1 / -0 )Share on Facebook
Sign In or Register to comment.