windows lua 多线程 线程同步

今天在改一个程序,改成部分逻辑用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

  • 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;