[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: coroutines & timeout
- From: Albert-Jan Brouwer <acj.brouwer@...>
- Date: Wed, 14 Apr 2004 14:23:27 +0200
Wilfried Verachtert wrote:
> For that, I realy need some kind of concurrent processes. The coroutines
> look nice (...)
> I don't need full fledged 'threads' because that probably would involve
> using the threads of the underlying OS. In my case, that would imply the
> installation of an OS on my embedded system and that's something I would
> like to avoid.
You can create an opcode counting hook and yield from there. The
problem with that is that the time taken up by a particular number of
opcodes can vary quite a bit. So it can be extended by calling the
hook very frequently and use it to poll a timer, and only yield when
that timer exceeds a set threshold.
Something as follows:
void opcodecounthook(lua_State *L, lua_Debug *ar) {
/* We can't yield across a metamethod/C-call boundary. */
if (L->nCcalls > 0) return;
/* See if more than the set threshold of time has passed since the last yield */
if ((MilliSecs()-yield_last) < yield_threshold) return;
lua_yield(L, 0);
}
The yield_last must be included as userstate with the lua
state, and set on resume as follows:
yield_last=MilliSecs();
For Lua code, this gives reasonably uniform cooperative time
slices. When the code being executed contains C calls that take
a long time to execute, latencies cannot be avoided since C calls
cannot be yielded. In particular this includes pcall and other
C library functions that take a function as parameter. Also,
coroutines cannot be used from within a resume.
Albert-Jan