Skip to content

Instantly share code, notes, and snippets.

@kjunichi
Last active January 9, 2024 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kjunichi/f6ba2d45f0eea269efa0af1584b62352 to your computer and use it in GitHub Desktop.
Save kjunichi/f6ba2d45f0eea269efa0af1584b62352 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <julia/julia.h>
#include <pthread.h>
JULIA_DEFINE_FAST_TLS
extern "C" double __stdcall c_func(int i);
extern "C" double __stdcall c_func(int i)
{
printf("[C %08x] i = %d\n", pthread_self(), i);
printf("c\n");
// 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));
printf("ccc\n");
return ret;
}
int main()
{
jl_init();
printf("c_func = %f\n", c_func(2));
// Define a Julia function func() that calls our c_func() defined in C above
jl_eval_string("func(i) = @ccall c_func(i::Int32)::Float64");
if (jl_exception_occurred())
printf("%s \n", jl_typeof_str(jl_exception_occurred()));
printf("a\n");
// Call func() multiple times, using multiple threads to do so
jl_eval_string("println(Threads.threadpoolsize())");
if (jl_exception_occurred())
printf("%s \n", jl_typeof_str(jl_exception_occurred()));
printf("aa\n");
jl_eval_string("use(i) = println(\"[J $(Threads.threadid())] i = $(i) -> $(func(i))\")");
if (jl_exception_occurred())
printf("%s \n", jl_typeof_str(jl_exception_occurred()));
printf("aaa\n");
jl_eval_string("val=2");
if (jl_exception_occurred())
printf("%s \n", jl_typeof_str(jl_exception_occurred()));
printf("aaabb\n");
jl_eval_string("println(val)");
if (jl_exception_occurred())
printf("%s \n", jl_typeof_str(jl_exception_occurred()));
jl_eval_string("ccall(:c_func,stdcall, Float32, (Int32,), val)");
if (jl_exception_occurred())
printf("%s \n", jl_typeof_str(jl_exception_occurred()));
printf("aaa use\n");
jl_eval_string("Threads.@threads for i in 1:5 use(i) end");
if (jl_exception_occurred())
printf("%s \n", jl_typeof_str(jl_exception_occurred()));
printf("aab\n");
jl_atexit_hook(0);
}

macos

build

cc main.c -I ~/.julia/juliaup/julia-1.10.0+0.x64.apple.darwin14/include -I ~/.julia/juliaup/julia-1.10.0+0.x64.apple.darwin14/include/julia -L ~/.julia/juliaup/julia-1.10.0+0.x64.apple.darwin14/lib -ljulia

RUN

JULIA_NUM_THREADS=8 DYLD_LIBRARY_PATH=~/.julia/juliaup/julia-1.10.0+0.x64.apple.darwin14/lib  ./a.out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment