lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


==========================
print "setup"

function hot_potato_1 ()
	while (1) do
		print ("co1: n is ".. n)
		if (n <= 0) then
			return
		else
			n = n-1
			cororesume (co2)
		end
	end
end

function hot_potato_2 ()
	while (1) do
		print ("co2: n is ".. n)
		if (n <= 0) then
			return
		else
			n = n-1
			cororesume (co1)
		end
	end
end

print "create"
co1 = coronew ("hot_potato_1")
co2 = coronew ("hot_potato_2")

n =  100
print ("start: "..n)
cororesume (co1)

print("done!")
corokill(co1)
corokill(co2)
read()
==========================

This sample (borrowed and re-adapted, from an old thread in the Python-coro
maillist) works. I am using Win32 fibers (which really are coroutines, not
different at all from the ones provided by the library coro-1.x.x and I did
not have to change anything at all in the Lua source code.
I have simply registered three functions (coronew, cororesume, corokill)
whose semantic should appear clear enough from my sample.
I only have one lua_State but every coroutine has its own L->stack, created
on coronew and swapped on the fly in L on every resume. To make sure the
garbage collector does not collect stuff from suspended coroutines
(including the one implicitly associated with main!) I have to copy on
coronew the entire content of the stack into the new stack. This is a real
waste of space (and possibly also of time) but so far I haven't found
another way to do this. Would it be possible to lock all the objects on the
stack of the parent of the new coroutine?
I believe that I should now be able to implement something in the direction
of Python's micro-threads.
I still have to figure out how to make a coresume return a result,
understand what happens to the longjmp chain used by Lua to unwind the stack
when exceptions are thrown, implement the scheduling mechanism (half C, half
Lua) and a few more of these minor issues :-)
The good points of the implementation are:
1) it's not platform independent but I know it could work on Linux and
FreeBSD without too much trouble;
2) there are no memory leaks (thanks to corokill);
3) no changes to the source files of the distribution of Lua are required,
although the sources must be kept synchronised in case something fundamental
changes in lua_State or luaD_Init or lmem.c;

In case you wonder, the output of the sample looks like this:
setup
create
start: 100
co1: n is 100
co2: n is 99

[and so on, until...]

co2: n is 1
co1: n is 0
done!
--
WildHeart'2k - mailto:stf@apl.it
Homepage: http://come.to/wildheart/


<<<... geeks smooching!?! ... ---
   WildHeart'98 productions>>>