今天在改一个程序,改成部分逻辑用lua写,这个程序是多线程的。将程序中部分逻辑改成lua之后,各种非法访问内存错误,各种奇奇怪怪的问题,不分时间,不分地点的出现崩溃。从调用堆栈来看,基本都是使用lua造成的。在多线程中使用lua_newthread得到的lus_State仍然有时候程序会崩溃。基本上可以确定为多线程中操作lua 的问题了。
前几天我转载的一篇文章,文章写了关于lua多线程的作法。作法有二
1.每一个线程函数用lua_newthread产生一个新的lua_state 以后对lua操作都用这个lua_state
2.修改lua源码使之成为支持多线程的(修改lua 源代码中lua_lock lua_unlock宏)
对于第2条,那篇文中的例子是用 pthread_mutex_t 来进行线程同步的pthread_mutex_t,我对pthread_mutex_t 不熟,网上一查才知道一般是在linux下C语言进行线程同步用的,在windows下面一般多线程都用CRITICAL_SECTION,和内核对象来进行线程同步的。于是产生了这篇文章。
修改代码如下:
1.global_State加一个成员变量 m_cs
Code Snippet
- typedef struct global_State {
- stringtable strt; /* hash table for strings */
- lua_Alloc frealloc; /* function to reallocate memory */
- void *ud; /* auxiliary data to `frealloc' */
- lu_byte currentwhite;
- lu_byte gcstate; /* state of garbage collector */
- int sweepstrgc; /* position of sweep in `strt' */
- GCObject *rootgc; /* list of all collectable objects */
- GCObject **sweepgc; /* position of sweep in `rootgc' */
- GCObject *gray; /* list of gray objects */
- GCObject *grayagain; /* list of objects to be traversed atomically */
- GCObject *weak; /* list of weak tables (to be cleared) */
- GCObject *tmudata; /* last element of list of userdata to be GC */
- Mbuffer buff; /* temporary buffer for string concatentation */
- lu_mem GCthreshold;
- lu_mem totalbytes; /* number of bytes currently allocated */
- lu_mem estimate; /* an estimate of number of bytes actually in use */
- lu_mem gcdept; /* how much GC is `behind schedule' */
- int gcpause; /* size of pause between successive GCs */
- int gcstepmul; /* GC `granularity' */
- lua_CFunction panic; /* to be called in unprotected errors */
- TValue l_registry;
- struct lua_State *mainthread;
- UpVal uvhead; /* head of double-linked list of all open upvalues */
- struct Table *mt[NUM_TAGS]; /* metatables for basic types */
- TString *tmname[TM_N]; /* array with tag-method names */
- CRITICAL_SECTION m_cs; /*windows mutithread */
- } global_State;
2.在lua_newstate加入初始化Critical_section的代码 InitializeCriticalSection(&g->m_cs);
Code Snippet
- LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) {
- int i;
- lua_State *L;
- global_State *g;
- void *l = (*f)(ud, NULL, 0, state_size(LG));
- if (l == NULL) return NULL;
- L = tostate(l);
- g = &((LG *)L)->g;
- L->next = NULL;
- L->tt = LUA_TTHREAD;
- g->currentwhite = bit2mask(WHITE0BIT, FIXEDBIT);
- L->marked = luaC_white(g);
- set2bits(L->marked, FIXEDBIT, SFIXEDBIT);
- preinit_state(L, g);
- g->frealloc = f;
- g->ud = ud;
- g->mainthread = L;
- g->uvhead.u.l.prev = &g->uvhead;
- g->uvhead.u.l.next = &g->uvhead;
- g->GCthreshold = 0; /* mark it as unfinished state */
- g->strt.size = 0;
- g->strt.nuse = 0;
- g->strt.hash = NULL;
- setnilvalue(registry(L));
- luaZ_initbuffer(L, &g->buff);
- g->panic = NULL;
- g->gcstate = GCSpause;
- g->rootgc = obj2gco(L);
- g->sweepstrgc = 0;
- g->sweepgc = &g->rootgc;
- g->gray = NULL;
- g->grayagain = NULL;
- g->weak = NULL;
- g->tmudata = NULL;
- g->totalbytes = sizeof(LG);
- g->gcpause = LUAI_GCPAUSE;
- g->gcstepmul = LUAI_GCMUL;
- g->gcdept = 0;
- InitializeCriticalSection(&g->m_cs);
- for (i=0; i<NUM_TAGS; i++) g->mt[i] = NULL;
- if (luaD_rawrunprotected(L, f_luaopen, NULL) != 0) {
- /* memory allocation error: free partial state */
- close_state(L);
- L = NULL;
- }
- else
- luai_userstateopen(L);
- return L;
- }
3.在close_state 加入删除CriticalSection的代码 DeleteCriticalSection(&g->m_cs);
Code Snippet
- static void close_state (lua_State *L) {
- global_State *g = G(L);
- luaF_close(L, L->stack); /* close all upvalues for this thread */
- luaC_freeall(L); /* collect all objects */
- lua_assert(g->rootgc == obj2gco(L));
- lua_assert(g->strt.nuse == 0);
- luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size, TString *);
- luaZ_freebuffer(L, &g->buff);
- freestack(L, L);
- lua_assert(g->totalbytes == sizeof(LG));
- DeleteCriticalSection(&g->m_cs);
- (*g->frealloc)(g->ud, fromstate(L), state_size(LG), 0);
- }
4.修改lua_lock和lua_unlock宏如下
Code Snippet
- #ifndef lua_lock
- #define lua_lock(L) EnterCriticalSection(&(G(L)->m_cs))
- #define lua_unlock(L) LeaveCriticalSection(&(G(L)->m_cs))
- #endif
5.为了使用CRITICAL_SECTION我们比较通用的方法是包含头文件 windows.h,但包含后发现,lua库中的LoadString函数正好与windows api LoadString同名。所以把lua库内部所使用的LoadString通通改为LUA_LoadString即可
修改完之后,在控制台写了四个线程一个一个主lua_state,四个线程使用lua_newthread得到的lua_state,没有再出现错误了。