Stack with concurrency support
Building upon the earlier implementation of stack, here is a simple implementation of a concurrent stack where we use the lock
keyword to stop any other thread from using the variable while it is in use. By obtaining the mutual-exclusion lock, the lock
keyword marks a statement block as a critical section. The lock is released after the statement is executed. The following example includes a lock statement to support concurrency. The lock
keyword signature follows.
lock : 'Lock -> (unit -> 'T) -> 'T (requires reference type)
To make this stack thread safe, we use lock
to allow the execution of the function in a critical section. The unit is the action which needs to be performed:
type ConcurrentStack<'T>() = let mutable _stack : List<'T> = [] member this.Push value = lock _stack (fun () -> _stack <- value :: _stack) member this.Pop() = lock _stack (fun () -> match _stack with | result :: remainder...