简体   繁体   中英

Mutable data with ocaml and jane street async

I am doing a project in OCaml using Jane Street's Async library for concurrency. I want to have multiple TCP servers taking inputs, whose handlers manipulate a single hashtable (a Hashtbl.t ). It seems like this scenario would require me to secure my hashtable with mutexes ( Mutex.t 's).

However, when I read the Async documentation and the chapter on Async in Real World Ocaml, I get the impression that there's an "async world" that uses Deferred.t 's and Pipe.t 's, and a "system thread world" that uses Threads and Mutexes, and the only way to mix them is to use the Thread_safe module, so I'm not really comfortable just throwing mutexes into my async computations.

So basically, how should I secure a shared mutable data structure when doing concurrent computations in async?

In general you do not need to secure with mutex some operation if it can be performed atomically. But this statement has different meanings depending on context.

In the context of async, the most strict definition of atomic operation is such operation that doesn't have type 'a Deferred.t . In other words, if it is not deferred, then it is atomic, and in the process of its execution it can't be interrupted by any other thread. Indeed, since async library implements cooperative threads, you always know whether given function can be interrupted or not, unlike with preemptive threads.

That means, that you can use any OCaml module, including of course hash tables, without any mutexes, since all their operations are atomic.

Mutexes are really rarely needed with cooperative multithreading. Usually, to implement transactions behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM