Carlos Cortez
Carlos Cortez

Reputation: 3

std::async not spawning a thread

I'm trying to process data in parallel using std::async but no thread is created nor the code is executed whatsoever for unknown reasons, the code is the following

std::vector<std::future<int>> threads;

for (DWORD offset = 0; offset < 10; offset++) {
    threads.push_back(std::async([](std::vector<unsigned int> sig, DWORD address, DWORD size)->int { 
        // Sleep is never called
        Sleep(5);
        // Only for test purposes anyway
        return 1;
        }, signature, 1, 1));
}

for (auto& thread : threads) {
    // Hangs here
    DWORD result = thread.get();

    if (result) {
        return (void*)result;
    }
}

For the sake of simplicity, i removed most of the useless code and left only the relevant part to the issue.

I tried debugging the code and setting a breakpoint in the Sleep api to check if anything is being executed but nothing happens; also, i can't seem to find any new threads in the process and the code hangs if i call thread.wait()/thread.get().

The code is compiled with visual studio 2019 community with /std:c++17

Upvotes: 0

Views: 216

Answers (1)

Carlos Cortez
Carlos Cortez

Reputation: 3

The function was being called from DllMain, the kernel object is created and scheduled but never executed because it waits for dllmain to finish loading but it never does, since it's waiting on the thread to execute first.

This question is kind of answered by raymond chen in his blog and i came across it before but it's just never obvious what is going on, testing the code on a clean project made me realize the code works just fine and made me realize something else was causing the threads to not spawn/run.

tl;dr: Creating threads during DllMain suspends their execution until dllmain finishes running.

Upvotes: 0

Related Questions