Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

[Threading] Best way to thread?

Asked by 9 years ago

Im just kinda wanting to know what is the BEST method to run a new function thread.

I know theres Delay / Spawn / Coroutine Is there anymore?

spawn(function()
    while true do
        --bleh
    end
end)

^^ Proven to be nice threading but does Rbx.Lua have anything better?

Please do not down vote; this is just a question to learn more about threading and script performance!

0
There is this type of code where you use the 'return' keyword, as I have seen it before, but, however, I do not know how it works at all, as I have never really seen it in action. :/ [return function() code end)] TheeDeathCaster 2368 — 9y

1 answer

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

First: Lua does not have true threads.

Coroutines work by starting whenever everyone else is stopped -- that is, when I yield, someone else can go (just like traffic). wait, :wait() etc are the normal ways that scripts yield.

That means there is a significant cost to making new coroutines that will work constantly -- because for each one, more and more time is spent just waiting and managing who goes next.

(There is a good reason for this -- it avoids race conditions)


If what you want is to just create and run a new coroutine, spawn is probably the best because it is clear and simple. delay equivalently so if you only want to make a new coroutine that will start after a given time.

Coroutines can do more, though. For example, it is an easy way to think of them as iterators. In that case, you could use coroutine.wrap or coroutine.create and coroutine.resume. But if you aren't explicitly using coroutine.yield it's unlikely you'll benefit from it.

In that case, spawn or delay is probably preferable.


NOTE: there isn't a "correct answer" answer to this. My answer represents only one opinion, and I'm sure there are good reasons to disagree with this at least in some situations.

I am also of the opinion that in general spawning coroutines is bad. Usually it is better (and it is almost always faster) if you manage to do things from a single thread rather than from multiple -- especially because you avoid strange race conditions.

0
So this means, long loops in others threads are bad? What about events? They don't stop the script's flow... FieryEvent 185 — 9y
Ad

Answer this question