Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Registration of C threads from callbacks #420

Merged
merged 3 commits into from
Aug 2, 2016
Merged

Registration of C threads from callbacks #420

merged 3 commits into from
Aug 2, 2016

Conversation

yallop
Copy link
Owner

@yallop yallop commented Aug 2, 2016

This pull request adds a new argument, ~thread_registration, to funptr. Passing ~thread_registration:true indicates that the C thread that calls into OCaml through the function pointer should be registered with the OCaml runtime (via caml_c_thread_register).

C threads so registered are automatically unregistered (via caml_c_thread_unregister) when they exit.

This functionality is currently unavailable on Windows, which apparently provides little support for running functions on thread termination. Perhaps it's possible to implement using RegisterWaitForSingleObject; patches are, of course, very welcome! (@fdopen: if you have time to look at this, your help would be greatly appreciated.)

Here's a quick example of the thread_registration in action, via a binding to pthread_create:

(* thread_example.ml *)
open Ctypes

let pthread_t = ulong

let pthread_create = Foreign.foreign "pthread_create"
    (ptr pthread_t @-> ptr void @->
     Foreign.funptr ~thread_registration:true ~runtime_lock:true
         (ptr void @-> returning (ptr void)) @->
     ptr void @-> returning int)
    ~release_runtime_lock:true

let pthread_join = Foreign.foreign "pthread_join"
    (pthread_t @-> ptr (ptr void) @-> returning int)
    ~release_runtime_lock:true

let callback p =
  print_endline "Hello, threaded world.";
  flush stdout;
  null

let _ = begin
  let thread_id = allocate_n pthread_t 1 in
  let _ = pthread_create thread_id null callback null in
  let _ = pthread_join !@thread_id (coerce (ptr void) (ptr (ptr void)) null) in
   ()
end
$ ocamlfind opt -package ctypes.foreign -thread -linkpkg  thread_example.ml
$ ./a.out 
Hello, threaded world.

This closes #269.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add flag to funptr to register calling threads with C.
1 participant