[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: A couple of thread questions...
- From: RLake@...
- Date: Wed, 18 Feb 2004 19:45:39 -0500
> Having created a thread using lua_newthread(),
is there a way to
> determine the status of the thread from C? That
is, whether it's
> waiting to be initialized (resumed for the first
time), waiting
> to be resumed as a result of yielding, or dead
(finished executing)?
I think you are confusing threads with coroutines.
A thread is simply an
auxiliary Lua state with its own stack.
A thread is always ready to run. You can at any moment
push a function
and arguments on a thread's stack, and call the function.
It never dies,
in other words. (That was a bit of an overstatement;
not doubt worthy
of a rejoinder from lhf -- there are some details
I haven't gone into.
But it is fundamentally true, nonetheless.)
Coroutines are built on top of threads, using a special
protocol
implemented with resume and yield. "yield"
transfers control to
another thread, in the middle of the yield call, as
it were.
"resume" causes the "yield" to
return. Consequently, you can
only resume if there is a "yield" on the
thread's call stack.
However, to make life a bit easier, you can call resume
on
a thread whose call stack is empty and whose stack
has a
function on the top (plus its arguments, if any).
When you lua_resume a coroutine and it returns (as
opposed to yielding),
its stack is cleaned; only the return values remain.
Once you have popped
(or more likely xmove'd) these return values, it is
ready to start again;
you can push a new function and args, and lua_resume
it.
You can tell roughly what state the thread is in.
lua_getstack(L1, 0, &ar)
will return 0 if the thread's call stack is empty.
lua_gettop(L1) will return
0 if the thread's current call frame has nothing in
it. If both of those are
true, the thread is not yielded. (After I figured
that out I checked the
code for coro.status, and that is the way it does
it, so it must be official :)
Personally, however, I would recommend using your
own protocol; for example,
always yield something and return nothing or vice
versa.
> Also, when exactly is a thread garbage collected?
Like anything else, when there is no longer any reference
to it. At that point,
its own stack has become unreachable, as well. Once
there is no longer any
reference to a thread, it may or not be dead, depending
on how you define
"dead" (as above, I would argue that it
is not meaningful, really),
but it certainly can never come back to life.
Hope that helps -- it was an interesting question
to answer.
Rici