This is a teaching sample intended to illustrate use of mutability and list consing in F#. The structure is intended to be a thread-safe stack structure, which multiple threads can push to/pop from concurrently. Concerns:
- Will this actually be thread safe?
- Are the locks necessary?
- Is there an immutable way to do the same thing? I don't think one can use the traditional immutable method here of having the Push/Pop return a new stack instance because different clients will see divergent views of the stack.
The code looks like this:
type ConcurrentStack<'T>() =
let mutable _stack : List<'T> = []
member this.Push value =
lock _stack (fun () ->
_stack <- value :: _stack)
member this.TryPop() =
lock _stack (fun () ->
match _stack with
| result :: newStack ->
_stack <- newStack
result |> Some
| [] -> None
)