[Q] Does `Thread` module really work?

Hello guys. I’m both a beginner in OCaml & CS, aka a noob.

I wrote this piece of code to test Thread module

let () = print_endline "Hello, World!"

let rec fib_normal (n: int): int =
    match n with
    | 0 | 1 -> n
    | x when x < 0 -> failwith "Negative number!"
    | _ -> fib_normal (n - 1) + fib_normal (n - 2)

let () =
    let _ = print_endline "With multi-threading:" in
    let handle_1 = Thread.create fib_normal 43 in
    let handle_2 = Thread.create fib_normal 43 in
    Thread.join handle_1; Thread.join handle_2;
    let _ = print_endline "Without multi-threading:" in
    let _ = fib_normal 43 in let _ = fib_normal 43 in ()

As you can see, this program

    1. Create 2 threads to run fibonacci function at the same time - they should be executed at the same time, thus it should cost half of the time to finish the task
    1. Run fib once, then run fib again - this should take longer cause it did not use threads

But the result is these 2 steps took the same time to finish, and CPU usage is always < 100%, which makes me wonder if OCaml < 5.0.0 has the same limitation as CPython (Global Interpreter Lock to make Python code unable to be executed parallelly)

I have hardly any knowledge of OCaml / Computer Science so excuse me for being a noob :slight_smile:

Have you tried using domains?

1 Like
  1. What is the timing data ? (ironic I’m asking this given how little timing data I’ve provided)

  2. Are you using ocamlc, ocamlopt, or byte code interpreter ?

1 Like

As the documentation states: “Only one thread at a time is allowed to run OCaml code” (and for OCaml 5, add “on a particular domain”).

1 Like

Yes, it does. You’d need to use Domains on OCaml 5.0+ to get what parallelism.

1 Like

I did, and loved it :smile: In fact, support for multi-threading(?) in OCaml 5 is the reason I started to learn OCaml because the feature sounds cool :crazy_face: Before that, the only language I know was Python (CPython, which has poor support for multi-threading)

I used TIMEFORMAT="%P%CPU" time dune exec thead_test to test, so I suppose it was ocamlopt? :thinking:

Thank you very much :smiling_face:

Actually, ignore everything I said. I’m also learning OCaml myself. I’m 99% sure the correct answer is: (it sounds confident and logical)

Thank you! I guess it doesn’t really matter cuz OCaml runs WAY TOO FAST even it was single-threaded :stuck_out_tongue_winking_eye: