Original Post
I use lua in game server .I want to listen an event in lua ,so I need create a new thread with the same lua evironment.But a strange error happeds :memory error.Check the following code: lua_bug.c You need compile the c file , gcc -fPIC -shared -olibbug.so lua_c.c -llua -ldl -lm -lpthread cp libbug.so /usr/lib then use the modul in lua script.Running lua file ,it will be Segmentation fault,or memory double free. The error will not appear every time ,or in a short time ,so you need test it more if the error does not show up. Also I test it without the lines " str = string.format("name%d",i);",the error shows up less. So can anyone tell me what happens ? Thank you
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <pthread.h>
/* args passed by thread
*/
typedef struct wrap_recv{
lua_State *Lr;
char func_name[124];
}WRAP_RECV;
static int recv_wrap(WRAP_RECV*wr){
pthread_detach(pthread_self());
lua_State *Lr = wr->Lr; //the child lua_State
char *fun = wr->func_name; //get the callback function name
int i = 0;
while(1){
lua_getglobal(Lr,fun);
lua_pushnumber(Lr,i);
lua_call(Lr, 1, 0);
i++;
}
}
static int lua_listen(lua_State *L) {
lua_State * Lr = NULL;
char *fun = (char*)lua_tostring(L, 1);
Lr = lua_newthread(L); //get a new lua_State
if (Lr == NULL)
luaL_error(L, "cannot create new stack");
/* create a hard reference to the thread object into the registry */
lua_pushlightuserdata(L, Lr);
lua_insert(L, -2);
lua_settable(L, LUA_REGISTRYINDEX);
WRAP_RECV*wr = (WRAP_RECV*)malloc(sizeof(WRAP_RECV));
wr->Lr = Lr;
strcpy(wr->func_name,fun);
pthread_t thread_id;
/* create a new thread of execution and we are done */
int res = pthread_create(&(thread_id), NULL, (void *) recv_wrap,
wr);
lua_pushinteger(L, res);
return 1;
}
static int lua_printtest(lua_State *L) {
int i = (int)lua_tointeger(L, 1);
printf("thread parent : %d\n",i);
return 0;
}
static luaL_Reg bugoperatelib[] = {
{ "listen", lua_listen },
{ "printtest", lua_printtest },
{ NULL, NULL } };
int init(lua_State*L) {
luaL_register(L, "bug", bugoperatelib);
return 1;
}
lua script
function fun_callback(pt)
print("thread child : "..pt)
end
package.loadlib("libbug.so", "init")();
bug.listen("fun_callback")
i = 1;
while i<5000000 do
str = string.format("name%d",i);
bug.printtest(i);
i = i+1;
end
while 1 do
end