lua-users home
lua-l archive

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


Hello, lua,
     I'm trying to use lua5.1.1 in c++ with multi os threads. But the garbage collection
confused me.  I put my code snippets here to get your help.   Thanks in advance.
       
    (1), comment (A) and uncomment (B), it seems to work well, when the memory gets to 44k,
         gc start, then memory is 21k,  as I expected.
    (2), comment (A) and comment (B),  I expect the memory increased to endless, but the memory
         gets to 48k and then decrease to 23k, and then loops. 
    (3), uncomment (A) and uncomment(B),  (C) is learned from the maillist to prevent gc the lua_state
         created by lua_newthread. But I am working with multi os threads, the gc may start before executing
         (C) (impossible???).  So I stop gc and then restart it.  I expect it works like (1).  However the
          memory increase quickly and never decrease.  
 
    Could you please point out what's wrong ?  
 
best regards,
-llazyworm
 
----
bool CLuaThread::Init(CLuaState * pMasterState)
{
 m_pMasterState = pMasterState;
 m_pMasterState->Lock();
 lua_State * L = m_pMasterState->GetVM();
 //lua_gc(L, LUA_GCSTOP, 0); //stop gc  (A)
 m_pThreadVM = lua_newthread(L);
 lua_pop(L, 1);
 lua_pushlightuserdata(L, m_pThreadVM);//(C) prevent gc
 lua_pushlightuserdata(L, this);       //(C)
 lua_settable(L, LUA_GLOBALSINDEX);    //(C)
  //lua_gc(L, LUA_GCRESTART, 0); //restart gc  (A)
 m_pMasterState->Unlock();
 return (m_pThreadVM != NULL);
}
 
void CLuaThread::Release()
{
 if (m_pMasterState && m_pThreadVM)
 {
//(B) 
//  m_pMasterState->Lock();
//  lua_State * L = m_pMasterState->GetVM();
//  lua_pushlightuserdata(L, m_pThreadVM);
//  lua_pushnil(L);
//  lua_settable(L, LUA_GLOBALSINDEX);
//  m_pMasterState->Unlock();
 }
}
 
int main()
{
 ...
 
  //test gc thread
  while (true)
 {
  CLuaThread * pT = new CLuaThread;
   bool rt = pT->Init(pLuaState);
   assert(rt);
   pT->Release();
  delete pT; 
  int memlua = lua_gc(pLuaState->GetVM(), LUA_GCCOUNT, 0);
  std::cout<<"mem used by lua "<<memlua<<std::endl;
 }
   return 0;
}