ocaml-containers icon indicating copy to clipboard operation
ocaml-containers copied to clipboard

add `CCLocal_storage` to containers-thread

Open c-cube opened this issue 3 years ago • 6 comments

Basic local storage emulation using an atomic-protected map. The goal is for this to work both with 4.xx threads, 5.xx domains, and 5.xx threads running on a given domain.

cc @bronsa :)

c-cube avatar Sep 14 '22 22:09 c-cube

A big design question is whether to pick:

  • never empty:

    type 'a t
    
    val create : init:(unit -> 'a) -> unit -> 'a t
    
    val get : 'a t -> 'a
    
  • can be empty (the current):

    type 'a t
    
    val create : unit -> 'a t
    
    val get : 'a t -> 'a option
    

c-cube avatar Sep 14 '22 23:09 c-cube

A big design question is whether to pick:

* never empty:
  ```ocaml
  type 'a t
  
  val create : init:(unit -> 'a) -> unit -> 'a t
  
  val get : 'a t -> 'a
  ```

* can be empty (the current):
  ```ocaml
  type 'a t
  
  val create : unit -> 'a t
  
  val get : 'a t -> 'a option
  ```

Why not both?

type 'a t

val create : init:(unit -> 'a) -> unit -> 'a t

val create_empty : unit -> 'a option t

val get : 'a t -> 'a

bronsa avatar Sep 14 '22 23:09 bronsa

If deleting the thread's local storage is not part of the API, I think it makes sense to have it always contain a value.

On the other hand, what would the behavior be when you create a new thread and pass the handle to it? Can you now get on the TLS and expect a value? The init function can only be called when you get. Should it be called also on a set from the new thread?

bluddy avatar Sep 15 '22 07:09 bluddy

@bluddy if it's always full, which makes sense, then: get v would initialize v if it was not already initialized for this thread; set v would just directly write the new value. You'd never observe an absence of values.

c-cube avatar Sep 15 '22 14:09 c-cube

@c-cube I'm just concerned about possible mutable state issues. In a regular array, init happens at once and is a lot more straightforward. In our case here, it happens only when you observe it, and doesn't happen at all if you don't observe it.

bluddy avatar Sep 15 '22 14:09 bluddy

Yeah I mean, if you do side-effectful stuff in a TLS initializer and then complain, it's kind of your fault :D. Unlike Array.init, the number of instances here is not fixed, and new threads might be started later, so initialization must be lazy.

c-cube avatar Sep 15 '22 14:09 c-cube

There's thread-local-storage already, and maybe it'll also land in the stdlib.

c-cube avatar Nov 20 '23 03:11 c-cube