Guest User

Untitled

a guest
Aug 26th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.86 KB | None | 0 0
  1. open System.Threading
  2. let mkThread f = Thread (ThreadStart f)
  3. let startThread f = (mkThread f).Start()
  4. let waitFor obj = ignore(Monitor.Wait obj)
  5. let wakeWaiters obj = Monitor.PulseAll obj
  6. let numClients = 5
  7.  
  8. let blahblah = ref false
  9.  
  10. type Client(clientID:int) =
  11.     let clients:Client[] ref = ref Array.empty
  12.     let inCharge = ref (if clientID=0 then true else false)
  13.     let usingNow = ref false
  14.     member this.ClientID = clientID
  15.  
  16.  
  17.  
  18.     member this.init(theClients) = clients:=theClients
  19.                                    startThread <| fun () ->
  20.                                         for i in 1..10 do
  21.                                             this.NewRequest i
  22.                                         printfn "Client %d: DONE WITH EVERYTHING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" clientID
  23.  
  24.  
  25.     member this.NewRequest exp = // Makes the client do a new request
  26.         lock this <| fun()->
  27.             while(not (!inCharge)) do
  28.                 inCharge := !clients |> Array.exists (fun cl -> cl.CanIHaveIt this.ClientID)
  29.    
  30.             usingNow:=true
  31.             printfn "Client %d: took charge" clientID
  32.             Thread.Sleep 100 // Only one client should do this at a time.
  33.             usingNow:=false
  34.             printfn "Client %d: Finished exp %d" clientID exp
  35.             lock blahblah <| fun()-> wakeWaiters blahblah
  36.            
  37.  
  38.     member this.CanIHaveIt clID = // Returns true when giving to the caller
  39.         lock blahblah <| fun()-> // printfn "Client %d: Request from client %d" clientID clID
  40.                                 while (!usingNow) do waitFor blahblah
  41.                                 let wasInCharge = !inCharge
  42.                                 inCharge:=false
  43.                                 wasInCharge
  44. let clients = Array.map (fun clID -> Client(clID)) [|0..numClients-1|]
  45. clients |> Array.iter (fun cl -> cl.init clients)
Add Comment
Please, Sign In to add comment