Embedded julia in multithread c++: examples and doc

Hi!
Im searching for a scripting language which scripts could be run in different threads.
No data share, only separate tasks. (with different math modules)
Julia seems to be able to work this way, but i found non of examples.
Only notes about jl_adopt_thread, and no explanation.

Which way i could learn julia embedding?

Is it good to use julia for embedding?

As example, code from doc is not compiling!
double (*sqrt_jl)(double) = jl_unbox_voidpointer(jl_eval_string("@cfunction(sqrt, Float64, (Float64,))"));
But fix is obvious

This might help:

Weaving threads across multiple programming languages is an extreme sport in software engineering. […]
jl_adopt_thread enables this C++ thread to be used by Julia. This is the most important C API function to remember for external multi-threading. It’s available since Julia 1.9.

And using:
https://clemens-cords.com/jluna/

2 Likes

Thanks for respons!
Try jluna but fall in non working multithreading - i even comment in existence issue on github, which designed in pre 1.9 way and didnt use jl_adopt_thread. Want to try to use older julia version to check origin of multithreading problem. Jluna seems incredibly promising in use, rather than pure api.

I also found the first one, but cant build this code due to lack of knowledge how (there is also missed files to include and some not compiled not documented functions mention in the post). Make another try to understand.

My hope is to directly study c api of julia to get minimal working example as starting point.

I even wrote one

JULIA_DEFINE_FAST_TLS


void thread(int (*test)(int), int count)
{
    jl_adopt_thread();

    double ret = test(count);

    std::cout << ret << std::endl;
}

int main(int argc, char *argv[])
{
    jl_init();

    jl_eval_string(R"(function Test(v::Int)
                        val = 0
                        for i in 1 : (v * 100)
                            val += i
                        end
                        return v
                      end)");

    int (*test)(int) = (int (*)(int)) jl_unbox_voidpointer(jl_eval_string("@cfunction(Test, Int, (Int,))"));

    std::thread all_threads[10];
    for(int i = 0; i < 10; ++i) {
        all_threads[i] = std::thread(thread, test, i);
    }

    // run all the threads
    for(auto& thread : all_threads)
        thread.join();

    return 0;
}

But there is no need in jl_adopt_thread(); it still working. And not working with print or sleep functions.

Could that be cfunction interface function is easy to use in threads? (until they print or sleep in its body)?

jl_adopt_thread is for adopting foreign threads from outside Julia. You do not need this if you initialize Julia with it’s own thread pool, for example via the -t command line option. You can also look up the JLOptions structure for a similar facility.

https://docs.julialang.org/en/v1/manual/multi-threading/