lua源码研究一些细节记录

  • LuaJIT版本编译64位,突破2gb内存限制
# Enable GC64 mode for x64.
#XCFLAGS+= -DLUAJIT_ENABLE_GC64
  • 多线程中的lua同步问题
修改 源码中llimits.h的
#define lua_lock(L) ((void)0)
#define lua_unlock(L)	((void) 0)
重写这两个宏。以添加pthread提供锁功能为例:
在lstate.h中,对GlobalState结构新加一个成员:
pthread_mutex_t lock;
然后在lua_newstate中添加初始化代码:
pthread_mutex_init(&g->lock, NULL);
接着重定义lock/unlock宏(写在原定义前面即可):
#define lua_lock(L) pthread_mutex_lock(&(G(L)->lock));
#define lua_unlock(L) pthread_mutex_unlock(&(G(L)->lock));
最后在close_state函数的末尾添加两行:

static void close_state (lua_State *L) {
  global_State *g = G(L);
  luaF_close(L, L->stack);  /* close all upvalues for this thread */
  luaC_freeallobjects(L);  /* collect all objects */
  luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size);
  luaZ_freebuffer(L, &g->buff);
  freestack(L);
  lua_assert(gettotalbytes(g) == sizeof(LG));
 pthread_mutex_unlock(&g->lock);
 pthread_mutex_destroy(&g->lock);
  (*g->frealloc)(g->ud, fromstate(L), sizeof(LG), 0);  /* free main block */
}
  • 字符串太多hash冲突导致lj_str_new调用过多效率问题
    可以参考openresty源码处理如下,改hash策略
static LJ_AINLINE uint32_t lj_str_hash(const char* str, size_t len)
{
  if (len < 128) {
    if (len >= 16) { /* [16, 128) */
      return lj_str_hash_16_128(str, len);
    }

    if (len >= 4) { /* [4, 16) */
      return lj_str_hash_4_16(str, len);
    }

    /* [0, 4) */
    return lj_str_hash_1_4(str, len);
  }
  /* [128, inf) */
  return lj_str_hash_128_above(str, len);
}

luajit原始版本

if (len >= 4) {  /* Caveat: unaligned access! */
    a = lj_getu32(str);
    h ^= lj_getu32(str+len-4);
    b = lj_getu32(str+(len>>1)-2);
    h ^= b; h -= lj_rol(b, 14);
    b += lj_getu32(str+(len>>2)-1);
  } else if (len > 0) {
    a = *(const uint8_t *)str;
    h ^= *(const uint8_t *)(str+len-1);
    b = *(const uint8_t *)(str+(len>>1));
    h ^= b; h -= lj_rol(b, 14);
  } else {
    return &g->strempty;
  }

其次减少字符串拼接,用table拼接。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值