1

I have a C++ dll application that is called from a Lua environment embedded in an executable. I need the dll "main" thread to spawn a thread to do it's thing, and let the main thread die to keep executing the Lua script that launched the dll. If I use join() the main thread doesn't return to Lua, if I don't the main thread terminates and kills the son. Is it even possible? Thanks for helping this noob :)

EDIT: Looks like detach() is what I'm looking for

void startThread() {
    initCommunication();
}

extern "C" __declspec(dllexport) int luaopen_myDLL(lua_State *L){
    // register Lua functions
    static const luaL_Reg functs [] = {
        {"registerOffsetMap", cpp_registerOffsetMap},
        {"registerLuaFile", cpp_registerLuaFile},

    ...

        {NULL,NULL}
    };

    luaL_register(L,"myDLL", functs);

    LuaGlobal = L;

    if (active) {
        return 0;
    }

    // run installed modules

    ...

    boost::thread thrd(startThread);
    thrd.detach();

    return 0; 
}

A Lua script calls require "myDLL" and runs the function luaopen_myDLL. That registers some functions in the dll so I can call them from Lua, and then should run the initComunication() function on it's own thread so the original Lua script can keep running.

Detach doesn't seem to work.

  • 1
    I didn't know threads were male. :-P – Marcelo Cantos Mar 25 '12 at 02:58
  • DLLs don't have a main thread. DLLs don't have *threads*. DLLs are bags of functions that other code will call. Can you explain with some code what exactly it is you're doing? – Nicol Bolas Mar 25 '12 at 03:09
  • Sorry, trying to figure out how to post code. Thanks Nicol. – user1290767 Mar 25 '12 at 03:43
  • Ok, I edited the original post to add some code and extra info – user1290767 Mar 25 '12 at 03:55
  • boost::thread_specific_ptr maybe? – user1290767 Mar 25 '12 at 05:02
  • If your code works with detach(), it will work without it. boost::thread instance anyway gets detached from its thread in the destructor. – Igor R. Mar 26 '12 at 11:19
  • By the way, it turns out that in C++11 thread object behaves differently: its d-tor doesn't detach automatically, but calls std::terminate instead: http://stackoverflow.com/questions/7241993/is-it-smart-to-replace-boostthread-and-boostmutex-with-c11-equivalents/7242294#7242294 – Igor R. Mar 27 '12 at 17:17

0 Answers0