Skip to content

Instantly share code, notes, and snippets.

@kjunichi
Last active December 20, 2024 01:13
Show Gist options
  • Save kjunichi/4e51f7290459d2b697bb0b450e82b5fb to your computer and use it in GitHub Desktop.
Save kjunichi/4e51f7290459d2b697bb0b450e82b5fb to your computer and use it in GitHub Desktop.
WindowsでpthreadをつかうJuliaの埋め込み

準備

vcpkgでpthreadを入れておく

vcpkg install pthreads:x64-windows

build

cl /I C:\vcpkg\vcpkg\installed\x64-windows\include /I C:\Users\kjwj\.julia\juliaup\julia-1.11.2+0.x64.w64.mingw32\in clude\julia main.cpp /link /LIBPATH:C:\Users\kjwj\.julia\juliaup\julia-1.11.2+0.x64.w64.mingw32\lib /LIBPATH:C:\vcpkg\vcpkg\installed\x64-windows\lib pthreadVC3.lib libjulia.dll.a libopenlibm.dll.a
#include <julia.h>
#include <pthread.h>
JULIA_DEFINE_FAST_TLS
extern "C" __declspec(dllexport)
double c_func(int i)
{
printf("[C %08x] i = %d\n", pthread_self(), i);
// Call the Julia sqrt() function to compute the square root of i, and return it
jl_function_t *sqrt = jl_get_function(jl_base_module, "sqrt");
jl_value_t* arg = jl_box_int32(i);
double ret = jl_unbox_float64(jl_call1(sqrt, arg));
return ret;
}
int main()
{
jl_init();
// Define a Julia function func() that calls our c_func() defined in C above
jl_eval_string("func(i) = ccall(:c_func, Float64, (Int32,), i)");
// Call func() multiple times, using multiple threads to do so
jl_eval_string("println(Threads.threadpoolsize())");
jl_eval_string("use(i) = println(\"[J $(Threads.threadid())] i = $(i) -> $(func(i))\")");
jl_eval_string("Threads.@threads for i in 1:5 use(i) end");
jl_atexit_hook(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment