async-std icon indicating copy to clipboard operation
async-std copied to clipboard

async-std in Windows cdylib dlls (LoadLibrary/FreeLibrary startup/cleanup)

Open Trolldemorted opened this issue 1 year ago • 1 comments

Is there a way to use async-std in Windows cdylibs that are being loaded/unloaded with LoadLibrary/FreeLibrary?

For this we'd have to ensure that before DllMain with PROCESS_DETACH returns, all threads that were spawned by async-std are no longer running. Unfortunately I do not have a clear overview over the intrinsic behaviour of async-std's thread pools, reactors (are they still a thing?) and whatnot, and the documentation was not that helpful in this particular matter.

What troubles me most are the special rules that apply to DllMain, such as "you cannot wait for threads to finish".

Trolldemorted avatar May 31 '23 22:05 Trolldemorted

You can add two exported functions to your DLL, and move initial/uninitial code from DllMain to new func, such as:

// cpp pseudo code
typedef void(*pFinishCb)();
__declspec(dllexport) void AsyncInitialize(pFinishCb cb) {
    std::thread([](){
        // do something...
        cb();
    }).detach();
}
__declspec(dllexport) void AsyncUninitialize(pFinishCb cb) {
    std::thread([](){
        // do something...
        cb();
    }).detach();
}

and wrap it to async rust func:

// rust pseudo code
async fn MyAsyncInitialize() {
    cpp::LoadLibrary();
    let (tx, rx) = mpsc::channel();
    cpp::AsyncInitialize(move ||{
        tx.send(());
    });
    rx.recv().await;
}
// and same to Unitialize

now you can async initialize/uninitialize your dll in async:

MyAsyncInitialize().await;

fawdlstty avatar Nov 29 '23 07:11 fawdlstty