多线程C Lua模块导致Lua脚本中的段错误

时间:2015-02-15 15:12:57

标签: c linux multithreading lua pthreads


我为Lua编写了一个非常简单的C库,它由一个启动线程的函数组成,所述线程除了循环之外什么都不做:

#include "lua.h"
#include "lauxlib.h"
#include <pthread.h>
#include <stdio.h>

pthread_t handle;
void* mythread(void* args)
{
    printf("In the thread !\n");
    while(1);
    pthread_exit(NULL);
}

int start_mythread()
{
    return pthread_create(&handle, NULL, mythread, NULL);
}

int start_mythread_lua(lua_State* L)
{
    lua_pushnumber(L, start_mythread());
    return 1;
}

static const luaL_Reg testlib[] = {
    {"start_mythread", start_mythread_lua},
    {NULL, NULL}
};

int luaopen_test(lua_State* L)
{
/*
    //for lua 5.2
    luaL_newlib(L, testlib);
    lua_setglobal(L, "test");
*/
    luaL_register(L, "test", testlib);
    return 1;
}

现在,如果我写一个非常简单的Lua脚本,那就是:

require("test")
test.start_mythread()

使用lua myscript.lua运行脚本有时会导致段错误。以下是GDB对核心转储的看法:

Program terminated with signal 11, Segmentation fault.
#0  0xb778b75c in ?? ()
(gdb) thread apply all bt

Thread 2 (Thread 0xb751c940 (LWP 29078)):
#0  0xb75b3715 in _int_free () at malloc.c:4087
#1  0x08058ab9 in l_alloc ()
#2  0x080513a2 in luaM_realloc_ ()
#3  0x0805047b in sweeplist ()
#4  0x080510ef in luaC_freeall ()
#5  0x080545db in close_state ()
#6  0x0804acba in main () at lua.c:389

Thread 1 (Thread 0xb74efb40 (LWP 29080)):
#0  0xb778b75c in ?? ()
#1  0xb74f6efb in start_thread () from /lib/i386-linux-gnu/i686/cmov/libpthread.so.0
#2  0xb7629dfe in clone () at ../sysdeps/unix/sysv/linux/i386/clone.S:129

主线程的堆栈有时会有一些变化。
似乎start_thread函数想要跳转到某个地址(在这个例子中,b778b75c),这个地址有时恰好属于无法访问的内存。
修改
我也有一个valgrind输出:

==642== Memcheck, a memory error detector
==642== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==642== Using Valgrind-3.10.0 and LibVEX; rerun with -h for copyright info
==642== Command: lua5.1 go.lua
==642== 
In the thread !
In the thread !
==642== Thread 2:
==642== Jump to the invalid address stated on the next line
==642==    at 0x403677C: ???
==642==    by 0x46BEEFA: start_thread (pthread_create.c:309)
==642==    by 0x41C1DFD: clone (clone.S:129)
==642==  Address 0x403677c is not stack'd, malloc'd or (recently) free'd
==642== 
==642== 
==642== Process terminating with default action of signal 11 (SIGSEGV): dumping core
==642==  Access not within mapped region at address 0x403677C
==642==    at 0x403677C: ???
==642==    by 0x46BEEFA: start_thread (pthread_create.c:309)
==642==    by 0x41C1DFD: clone (clone.S:129)
==642==  If you believe this happened as a result of a stack
==642==  overflow in your program's main thread (unlikely but
==642==  possible), you can try to increase the size of the
==642==  main thread stack using the --main-stacksize= flag.
==642==  The main thread stack size used in this run was 8388608.
==642== 
==642== HEAP SUMMARY:
==642==     in use at exit: 1,296 bytes in 6 blocks
==642==   total heap usage: 515 allocs, 509 frees, 31,750 bytes allocated
==642== 
==642== LEAK SUMMARY:
==642==    definitely lost: 0 bytes in 0 blocks
==642==    indirectly lost: 0 bytes in 0 blocks
==642==      possibly lost: 136 bytes in 1 blocks
==642==    still reachable: 1,160 bytes in 5 blocks
==642==         suppressed: 0 bytes in 0 blocks
==642== Rerun with --leak-check=full to see details of leaked memory
==642== 
==642== For counts of detected and suppressed errors, rerun with: -v
==642== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Killed


但是,到目前为止我只是打开lua解释器并一个接一个地手动输入相同的指令。
此外,C程序使用相同的lib执行相同的操作:

int start_mythread();

int main()
{
    int ret = start_mythread();
    return ret;
}

应该,在我的测试中从未失败过。
我尝试过Lua 5.1和5.2,但没有用。
编辑我应该指出我在运行32位Debian Wheezy(Linux 3.2)的单核eeePC上进行了测试。 我刚刚在我的主机(4核64位Arch linux)上再次测试,每次启动lua myscript.lua段错误的脚本。 。 从解释器提示输入命令可以正常工作,以及上面的C程序。
我之所以写这篇小文章是因为我写了一个更大的图书馆,我首先遇到了这个问题。经过几个小时的无效调试,包括逐个删除每个共享结构/变量(是的,我是绝望的),我已经归结为这段代码。
所以,我的猜测是我在Lua身上做错了什么,但那会是什么呢?我尽可能多地搜索了这个问题,但我发现的主要是人们在使用几个线程中的Lua API时遇到了问题(这不是我在这里尝试做的事情)。
如果您有任何想法,我们将非常感谢您的帮助。

修改
更确切地说,在编写用于Lua脚本的C lib时,我想知道是否应该对线程采取额外的预防措施。 Lua 是否需要在动态加载的库中创建的线程在#&#34;卸载&#34;图书馆?

2 个答案:

答案 0 :(得分:2)

为什么Segaault会在Lua模块中发生?

您的Lua脚本在线程完成之前退出,这会导致段错误。在正常的解释器关闭期间,使用dlclose()卸载Lua模块,因此线程的指令从内存中删除,并且在读取下一条指令时会出现段错误。

有哪些选择?

任何在卸载模块之前停止线程的解决方案都可以。在主线程中使用pthread_join()将等待线程完成(您可能希望使用pthread_cancel()终止长时间运行的线程)。在卸载模块之前在主线程中调用pthread_exit()也可以防止崩溃(因为它会阻止dlclose()),但它也会中止Lua解释器的正常清理/关闭过程。

以下是一些有用的示例:

int pexit(lua_State* L) {
   pthread_exit(NULL);
   return 0; 
} 

int join(lua_State* L)
{
  pthread_join(handle, NULL);
  return 0;
}

static const luaL_Reg testlib[] = {
    {"start_mythread", start_mythread_lua},
    {"join", join},
    {"exit", pexit},
    {NULL, NULL}
};

void* mythread(void* args) {
  int i, j, k;
    printf("In the thread !\n");
    for (i = 0; i < 10000; ++i) {
      for (j = 0; j < 10000; ++j) {
        for (k = 0; k < 10; ++k) {
          pow(1, i);
        }
      }
    }
    pthread_exit(NULL);
}

现在脚本将很好地退出:

require('test')
test.start_mythread()
print("launched thread")
test.join() -- or test.exit()
print("thread joined")

要自动执行此操作,您可以绑定到垃圾回收器,因为在卸载共享对象之前,模块中的所有对象都已释放。 (正如大狼所说)

  

Discussion on calling pthread_exit() from main(): 如果main()在产生的线程之前完成,则存在明确的问题   你没有明确地调用pthread_exit()。它的所有线程   created将终止,因为main()已完成且不再存在   支持线程。通过让main()显式调用pthread_exit()   作为它做的最后一件事,main()将阻止并保持活着   支持它创建的线程,直到它们完成。

(这句话有点误导:从main()返回大致相当于调用exit(),这将退出包括所有正在运行的线程的进程。这可能是也可能不是你想要的行为。另一方面,在主线程中调用pthread_exit()将退出主线程,但保持所有其他线程运行,直到它们自行停止或其他人杀死它们。再次,这可能是也可能不是你想要的行为。除非你为你的用例选择了错误的选项,否则没有问题。)

答案 1 :(得分:0)

所以,似乎我必须确保在Lua卸载我的lib时我的所有线程都已完成。

解决方案

我可以设置一个清理函数,以便在卸载库时调用 在这个函数中,我可以确保我的lib开始的所有线程都已终止。如果我有分离的线程仍然在运行,那么从它调用pthread_exit可能很容易,但是我不确定它是多么安全/清洁,因为它会突然中断Lua ...
无论如何,我可以通过创建一个设置为我的清理函数的__gc字段的metatable来实现这一点,然后在Lua 5.2中将这个metatable影响到我的lib表。

int cleanup(lua_State* L)
{
    /*Do the cleaning*/
    return 0;
}

int luaopen_test(lua_State* L)
{
    //for lua 5.2
    //metatable with cleanup method for the lib
    luaL_newmetatable(L, "test.cleanup");
    //set our cleanup method as the __gc callback
    lua_pushstring(L, "__gc");
    lua_pushcfunction(L, cleanup);
    lua_settable(L, -3);
    //open our test lib
    luaL_newlib(L, testlib);
    //associate it with our metatable
    luaL_setmetatable(L, "test.cleanup");

    return 1;
}

在Lua 5.1中,__gc选项仅适用于userdata。在我的案例中有几种解决方案可以让它发挥作用:
- Lua shutdown/End of the program execution callback
- http://lua-users.org/wiki/LuaFaq(请参阅&#39;为什么__gc和__len元方法不能用于表格?&#39;)
- Greatwolf的解决方案是拥有一个带有所述metatable的全局对象。