Why OCaml has Mutex module?

As far as I know, OCaml does offer concurrency but not parallelism (Why OCaml's threading is considered as `not enough`?)

Then why does OCaml still offer Mutex module and provide lock ?

If no two threads can run simultaneously, then why we still need lock ?


In general there are critical regions in code modifying data shared between threads that leave that data in an inconsistent state. This is precisely the same problem as when there are simultaneously executing processes. As @nlucaroni points out, a context switch in the middle of a critical region should not allow another thread into the same critical region. For example:

(* f should count the number of times it's called *)
let f = 
  let x = ref 0 in
  fun () -> 
    x := !x + 1;
    !x

A context switch after the lookup of x but before the store can clearly result in a miscount. This is fixed with a mutex.

(* f should count the number of times it's called *)
let f = 
  let x = ref 5 in
  let m = Mutex.create () in
  fun () -> 
    Mutex.lock m;
    x := !x + 1;
    let ret = !x in
    Mutex.unlock m;
    ret

will fix this.


Because mutex is a concurrency primitive, not specific for parallelism. It is used to make execution of piece of code atomic from the point of view of other concurrent entities. It is used to organize exclusive access to specific portion of data while executing specific piece of code (eg to ensure that only single concurrent thread of execution is modifying data breaking the invariants in process but restoring those invariants before releasing the mutex so that other concurrent threads of execution will see consistent data when they get access to it).

链接地址: http://www.djcxy.com/p/79344.html

上一篇: 在OCaml中,这是什么类型的定义:'a。 单元

下一篇: 为什么OCaml有互斥模块?