[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: What's the difference between a "coroutine" and a "thread" in Lua?
- From: "Gregg Reynolds" <dev@...>
- Date: Fri, 10 Aug 2007 10:58:36 -0500
On 8/10/07, Asko Kauppi <firstname.lastname@example.org> wrote:
> Suggestion to the Lua authors:
> In next version, you might consider using "coroutine" everywhere
> where thread now is (including the type name!). This is because
> With multithreading packages, there will be "threads" (the threads
> the packets provide, Lua constructs) and "OS threads" (the underlying
> threads, which might or might not have a 1:1 mapping to Lua threads).
> And OS threads map to kernel and user threads.... :)
I strongly second. From the manual:
"The type thread represents independent threads of execution and it is
used to implement coroutines (see §2.11). Do not confuse Lua threads
with operating-system threads. Lua supports coroutines on all systems,
even those that do not support threads."
"A coroutine in Lua represents an independent thread of execution.
Unlike threads in multithread systems, however, a coroutine only
suspends its execution by explicitly calling a yield function."
Q: when is a thread not a thread? A: (...your witticism here...)
For me at least this language is pretty confusing. However, I can see
the wisdom of distinguishing between coroutine (which is perforce a
kind of routine, function, or the like) and a thread (qua machine
state, execution context, whatever). I suggest renaming type thread;
the wikipedia article on thread suggests a useful term:
"In this article, the term "thread" is used to refer to kernel
threads, whereas "fiber" is used to refer to user threads. Fibers are
co-operatively scheduled: a running fiber must explicitly "yield" to
allow another fiber to run. A fiber can be scheduled to run in any
thread in the same process...Many fiber implementations are entirely
in userspace. As a result, context switching between fibers within the
same process is extremely efficient because it does not require any
interaction with the kernel at all: a context switch can be performed
by locally saving the CPU registers used by the currently executing
fiber and then loading the registers required by the fiber to be
executed. Since scheduling occurs in userspace, the scheduling policy
can be more easily tailored to the requirements of the program's
Does the lua type thread fit this description? If so I would heartily
recommend using "fiber".