lua-users home
lua-l archive

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


Lua threads and C threads are very different things. Lua threads are
for co-operative multi-threading independently of the OS. The closest
OS equivalent to a Lua thread is a fibre. A Lua global state and it's
associated Lua threads should only be used by one OS thread at any
moment in time. If a global state is used by more than one OS thread
simultaneously, then segmentation faults will (eventually) occur.

On Fri, Jun 19, 2009 at 7:44 PM, 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
>
>