Content deleted Content added
→Agent programming: replaced the example with concurrent queue implementation with mailboxprocessor. |
|||
Line 539:
===Agent programming===
F# supports a variation of the [[Actor model|Actor]] programming model through the in-memory implementation of lightweight asynchronous agents. For example, the following code defines an agent and posts 2 messages:
<syntaxhighlight lang="fsharp">
type Message =
| Enqueue of string
MailboxProcessor.Start(fun inbox ->▼
| Dequeue of AsyncReplyChannel<Option<string>>
// Provides threads concurrent access to a list of strings
let! msg = inbox.Receive()▼
▲ let listManager = MailboxProcessor.Start(fun inbox ->
return! loop(n+msg) }▼
match msg with
| Enqueue item ->
return! messageLoop (item :: list)
| Dequeue replyChannel ->
match list with
| [] ->
replyChannel.Reply None
| head :: tail ->
replyChannel.Reply (Some head)
return! messageLoop tail
}
// Start the loop with an empty list
messageLoop []
)
// Usage
async {
// Enqueue some strings
listManager.Post(Enqueue "Hello")
listManager.Post(Enqueue "World")
// Dequeue and process the strings
let! str = listManager.PostAndAsyncReply(Dequeue)
str |> Option.iter (printfn "Dequeued: %s")
}
|> Async.Start
</syntaxhighlight>
|