Version française
Home     About     Download     Resources     Contact us    
Browse thread
calling ocaml from threaded C program
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Markus Mottl <markus.mottl@g...>
Subject: Re: [Caml-list] calling ocaml from threaded C program
On 1/8/07, Trevor Jim <trevor@research.att.com> wrote:
>
> However, I still get crashes.  I think I must be missing some locking.
> So far I have locked ObjC calls to caml_callback, caml_callback_exn,
> etc.  I have not locked certain other calls of the caml C API, e.g.,
>
>    caml_named_value()
>    caml_copy_string()
>    caml_remove_global_root()
>    caml_register_global_root()
>    Val_int()
>    Field()
>    String_val()
>    Wosize_val()


With the exception of "Val_int" none of the above is thread-safe.  Since the
GC can move values at anytime while your C-thread is executing, any
C-function that accepts or returns a "value" (= OCaml-value) is potentially
unsafe.  Val_int is an exception, because OCaml-ints are unboxed (btw.
unlike int32, int64, nativeint!).  Atomic (also atomic polymorphic) variants
and characters, too, are unboxed and can therefore be safely handled by
C-threads at any time.

Furthermore, it is safe to access the contents of bigarrays if they cannot
be reclaimed during that time (e.g. because you protected them before
releasing the OCaml-lock using CAMLparam, etc.), because their contents is
outside of the OCaml-heap.

Otherwise never access OCaml-values from a C-thread if there are running
OCaml-threads.  Here be dragons...

If anyone knows exactly what parts of the ocaml C API need to be locked
> for this scenario, it would be nice to have that in the documentation.


Yes, that would be nice indeed...

Also, I wonder whether there is any issue with having one ObjC thread
> in the ocaml runtime, while another ObjC thread accesses an object
> that is either an ocaml root or accessible from an ocaml root -- is
> any locking required?


The OCaml-GC may run at anytime and mess with the existence and position of
OCaml-values.  Thus, you cannot do what you want here without locking.

Regards,
Markus

-- 
Markus Mottl        http://www.ocaml.info        markus.mottl@gmail.com