lua-users home
lua-l archive

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


Hello Marc,

Lua threads aren't related to OS threads at all - they're just
coroutines.  Please read the chapter on coroutines (chapter 9 in PIL
v1), and check out LuaLanes or one of the other fine threading
libraries for all your Lua multithreading needs.  In short, it's
segfaulting because Lua and OS threads don't mix =(.

-Rob Hoelz

On Fri, 19 Jun 2009 20:44:41 +0200
Marc Vollmer <marc.vollmer@googlemail.com> wrote:

> Hi all!
> 
> I have a problem with lua and threads. The C program starts, but
> after a few loops the program terminates with segmentation fault.
> It's same problems with linux and windows (access violation).
> 
> Can someone tell me why an segmentation fault happened? Or better,
> what am I doing wrong?
> 
> Below I have attached the programs.
> 
> Thx
> Marc
> 
> ------------------------------------------
> -- C program
> ------------------------------------------
> #include <stdio.h>
> #include <pthread.h>
> #include "lua.h"
> #include "lauxlib.h"
> #include "lualib.h"
> 
> lua_State *masterState;
> lua_State *workerState;
> pthread_t a_thread;
> int stop=0;
> 
> void *thread_function(void *arg){
>   while (stop==0) {
>     luaL_loadfile(workerState,"print.lua");
>     lua_pcall(workerState, 0, 0, 0);
>   }
>   pthread_exit(0);
> }
> 
> int main() {
>   long loop;
>   masterState = luaL_newstate();
>   luaL_openlibs(masterState); 
>   workerState = lua_newthread(masterState);
>   pthread_create(&a_thread,NULL, thread_function, NULL);
>   for (loop=0; loop<1000000; loop++) {
>     printf("Mem: %d\n",lua_gc(masterState,LUA_GCCOUNTB,0)*1024);
>     luaL_loadfile(masterState,"fib.lua");
>     lua_pcall(masterState, 0, 0, 0);
>   }
>   stop=1;
>   printf("finish");
>   return 0;
> }
> 
> ------------------------------------------
> -- fib.lua
> ------------------------------------------
> function fastfib(n)
>   fibs={[0]=0, 1, 1} -- global variable, outside the function
>   for i=3,n do
>     fibs[i]=fibs[i-1]+fibs[i-2]
>   end
>   return fibs[n]
> end
> a=fastfib(10)
> print("fastfib: "..a)
> 
> ------------------------------------------
> -- print.lua
> ------------------------------------------
> for i=1,5 do
>   print("lua loop "..i)
> end
> 

Attachment: signature.asc
Description: PGP signature