tonyw
tonyw

Reputation: 13

Efficient way to create Lua threads?

a quick question regarding threading in Lua via c++ game engine...

I am wondering about the efficiency of creating Lua threads. It doesn't look like something we want to be doing a lot as it seems that each time a thread is creating there is a big copy of the Lua chunk. So -

lua_State *L = luaL_newstate();
luaL_openlibs(L);

lua_State *thread = lua_newthread(L);
luaL_loadfile(thread, "luac1.bin"); // or luaL_loadbuffer or ?
lua_resume(thread, NULL, 0);

The new thread always involves the copying of the chunk data, and when the thread ends the chunk is lost I believe. Is there an efficient way to be able to spawn these threads over and over without any chunk copy each time?

[edit] I should add that these are threads as they will likely want to Yield before they end.

thanks

Upvotes: 1

Views: 4574

Answers (1)

Cauterite
Cauterite

Reputation: 1694

What you're looking for is lua_xmove: "Exchange values between different threads of the same state."

lua_State* L = luaL_newstate();
luaL_openlibs(L);

lua_State* thread1 = lua_newthread(L);
lua_State* thread2 = lua_newthread(L);

// load chunk as a function and copy it to the top of each thread's stack
luaL_loadfile(L, "luac1.bin");
lua_pushvalue(L, -1);
lua_xmove(L, thread1, 1);
lua_pushvalue(L, -1);
lua_xmove(L, thread2, 1);

lua_resume(thread1, NULL, 0);
lua_resume(thread2, NULL, 0);

This way you only have to load the chunk once. the threads are all sharing the same instance.

Upvotes: 2

Related Questions