Clemapfel / jluna

Julia Wrapper for C++ with Focus on Safety, Elegance, and Ease of Use
https://clemens-cords.com/jluna
MIT License
237 stars 12 forks source link

Multi-threading example is not multi-threading #57

Open lucwens opened 9 months ago

lucwens commented 9 months ago

On Windows 10 and with julia 1.9.3-64 bit, the multi-threading examples from the documentation do not seem to multi-thread. The supposedly multi-threading tasks are executed in the main thread upon calling join(), they do not start before the sleep_for statement in main.

include

include

include

JULIA_DEFINE_FAST_TLS // only define this once, in an executable (not in a shared library) if you want fast code.

using namespace std; using namespace jluna;

int main(int argc, char* argv[]) { jluna::initialize(8); std::vector<Task> tasks; { // declare lambda std::function<void()> print_numbers = []() -> void { for (size_t i = 0; i < 10000; ++i) if (i%100 == 0) std::cout << i << std::endl; };

    // add task to storage
    tasks.push_back(ThreadPool::create(print_numbers));

    // wait for 1ms
    std::this_thread::sleep_for(1ms);
}

for (auto& Task : tasks)
    Task.schedule();

// wait for another 10ms
std::this_thread::sleep_for(10000ms);
std::cout << "Main waited 10 sec" << std::endl;

for (auto& Task : tasks)
    Task.join();

return 0;

}

Clemapfel commented 7 months ago

Your code does not compile for me, after correcting the missing template argument in std::vector<Task> and the lambda capture clause of print_numbers, it runs for me as expected

jluna::initialize(8);
std::vector<Task<void>> tasks;
{
    // declare lambda
    std::function<void()> print_numbers = []() -> void
    {
        for (size_t i = 0; i < 10000; ++i)
            if (i%100 == 0)
                std::cout << i << std::endl;
    };

    // add task to storage
    tasks.push_back(ThreadPool::create(print_numbers));

    // wait for 1ms
    std::this_thread::sleep_for(1ms);
}

for (auto& Task : tasks)
    Task.schedule();

// wait for another 10ms
std::this_thread::sleep_for(10000ms);
std::cout << "Main waited 10 sec" << std::endl;

for (auto& Task : tasks)
    Task.join();
...
9700
9800
9900
Main waited 10 sec

I will try to test this on my windows 10 machine as well

lucwens commented 7 months ago

I still get this result [JULIA][LOG] initialization successful (1 thread(s)). Main waited 10 sec 0 100 200 300 400 500 600 700 800 900

This is with Julia 9.1.4 in Visual Studio 2022 on Windows 10 and using the source from your reply, so quite puzzled why we get a different result. Zip of project added for your reference Julia2.zip