F# a Concurrency rubrika: Programování: Jiné
položil/-a 2.3.2013
podla navodu na zasobnik wikibooks http://en.wikibooks.org/wiki/F_Sharp_Programming/MailboxProcessor
som si napisal vlastne atomicke thread safe key-value ulozisko. V navode na wikibooks sa pouziva PotAndAsyncReply len pri citani nemalo by sa pouzit aj pri zapise? metody Set a Delete by nemali nahodou vracat asynchronny vysledok s prazdnou hodnotou (Async<unit>) ?
type KeyValueStorage_Message = | Set of string * string | Delete of string | Get of string * AsyncReplyChannel<string> | ContainsKey of string * AsyncReplyChannel<bool> | GetAll of AsyncReplyChannel<Map<string, string>> type KeyValueStorage_Agent(storage : Map<string, string>) = let mbox = MailboxProcessor.Start (fun inbox -> let rec loop storage = async { let! msg = inbox.Receive() let storage = match msg with | Set (key, vlaue) -> storage |> Map.add key vlaue | Delete key -> storage |> Map.remove key | Get (key, reply) -> reply.Reply(storage.[key]) storage | GetAll (reply) -> reply.Reply(storage) storage | ContainsKey (key, reply) -> reply.Reply(storage.ContainsKey(key)) storage return! loop storage } loop storage) member a.Set(key, value) = mbox.Post(Set(key, value)) member a.Delete(key) = mbox.Post(Delete key) member a.Get(key) = mbox.PostAndAsyncReply(fun channel -> Get(key, channel)) member a.ContainsKey(key) = mbox.PostAndAsyncReply(fun channel -> ContainsKey(key, channel)) member a.ToMap() = mbox.PostAndAsyncReply(fun channel -> GetAll(channel)) member a.Item with get key = a.Get(key) and set key value = a.Set(key, value) new() = KeyValueStorage_Agent(Map.empty)
Pro plný přístup na Devel.cz se prosím přihlaste:
Nebo se přihlaste jménem a heslem:
Komentáře