SlideShare a Scribd company logo
1 of 29
Concurrent programming with Agents
Tomáš Petříček
http://tomasp.net/blog
http://twitter.com/tomaspetricek
Introducing agents
Inside agent’s brain
Inter-agent communication
Reusable agents
Intelligence networks
Sequential programs
Task based parallelism
Agent-based concurrency
Agent-based concurrency
Programs compose from agents
Instead of functions or objects
Agents exchange messages
Receive message and react
Reactive system
Handle inputs while running
Emit results while running
Example
Introducing agents
Simple chat room
Functional loop with single state
Single state
Same reaction to all messages
Implemented using recursive loop
What if reaction depends on the state?
What if agent cannot handle some message?
Immutable state
Maintained as parameter of recursive function
Can use mutable collections for performance
Hiding agent’s brain
Accessing agent directly
Exposes implementation details
Users can call wrong methods (e.g. Receive)
Encapsulating agent
Agent as a private filed
Add methods for all (public) messages
Expose asynchronous calls first
Example
Encapsulating agent into an object
Exposing chat room via HTTP
Hiding agent’s brain
 Asynchronous calls from F#
 Synchronous calls from F# (optional)
 Asynchronous calls from C# (task based)
member x.AsyncGetContent(?timeout) =
agent.PostAndAsyncReply(GetContent, ?timeout=timeout)
member x.GetContent(?timeout) =
agent.PostAndReply(GetContent, ?timeout=timeout)
member x.GetContentAsync() =
Async.StartAsTask(agent.PostAndAsyncReply(GetContent))
member x.GetContentAsync(cancellationToken) =
Async.StartAsTask(agent.PostAndAsyncReply(GetContent),
cancellationToken=cancellationToken)
Introducing agents
Inside agent’s brain
Inter-agent communication
Reusable agents
Intelligence networks
Inside agent’s brain
Single state
Accept and react
to all messages
Example: Twitter status agent with pause
Resume
Pause
d
Running
Resume Status
Pause
Multiple states
Agent implements a
state machine
Example
Reading statuses from Twitter
Pausing the stream using blocking agent
State and state transitions
Accepting all messages
Asynchronously Receive and use pattern matching
Waiting for specific message
Other messages stay in the queue
Writing message handling using Scan
let rec state = agent.Scan(function
| Message -> Some <| async {
handleMessage()
return! newState }
| _ -> None )
Introducing agents
Inside agent’s brain
Inter-agent communication
Reusable agents
Intelligence networks
Inter-agent communication
Direct links between agents
Complicates reusability and reconfiguration
Decoupling using events
Expose event instead of sending message
We used events in the previous example!
Types of agent’s members
Send message to the agent
Members of type: 'T -> unit
Notifications from the agent
Exposed as events or observables: IObservable<'T>
No synchronization and no thread guarantees
Send and wait for a reply
Uses asynchronous reply channels from F# library
Takes arguments and returns result: 'T -> Async<'R>
Connecting agents
Sending message in response to notification
Alternatively, Observable.subscribe supports removal
Connecting agents with asynchronous actions
Create and start asynchronous workflow
source.Notification |> Observable.add target.Action
async { while true do
let! value = source.AsyncAction()
do! target.Action(value) }
|> Async.Start
Introducing agents
Inside agent’s brain
Inter-agent communication
Reusable agents
Intelligence networks
Reusable agents I.
Aggregating messages into bulks
Bulk specified number of messages
Emit bulk after timeout
Uses of bulking agent
Grouping data for further processing
Writing live data to a database
new BulkingAgent : int -> int -> BulkingAgent
member Enqueue : 'T -> unit
member BulkProduced : Event<'T[]>
Example
Bulk processing of Twitter statuses
A look at the BulkingAgent implementation
Reusable agents II.
Blocking queue with limited size
Block reader when queue is empty
Block adder when queue is full
Uses of blocking queue agent
The producer consumer pattern
Immediate buffer in pipeline processing
new BlockingQueueAgent : int -> BlockingQueueAgent
member AsyncGet : unit -> Async<'T>
member AsyncAdd : 'T -> Async<unit>
Introducing agents
Inside agent’s brain
Inter-agent communication
Reusable agents
Intelligence networks
Managing intelligence network
 Lots of things going on!
How to keep a big picture?
Using loosely coupled connections
Agents don’t reference each other directly
Common ways of organizing agents
Worker agent – Single agent does all the work
Layered network – Agent uses agents from lower level
Pipeline processing – Step-by-step processing
Pipeline processing
Values processed in multiple steps
Worker takes value, processes it, and sends it
Worker is blocked when source is empty
Worker is blocked when target is full
Steps of the pipeline run in parallel
Example
Pipeline image processing
Summary
Why use agent-based concurrency?
Easy to understand reactive applications
Elegant implementation of concurrent patterns
How to write an agent-based application?
State machine using recursive functions
Encapsulate and provide communication points
(send and send & reply methods and notifications)
Use reusable agents for recurring patterns
Questions?
Email: tomas@tomasp.net
Blog: http://tomasp.net/blog
Twitter: http://twitter.com/tomaspetricek
My book: http://functional-programming.net

More Related Content

Similar to Concurrent programming with Agents

Web Services 8
Web Services 8Web Services 8
Web Services 8
pradeepfdo
 
Delegates and events
Delegates and eventsDelegates and events
Delegates and events
Iblesoft
 
Design patterns - ICIN 2010
Design patterns - ICIN 2010Design patterns - ICIN 2010
Design patterns - ICIN 2010
steccami
 
Restate: Event-driven Asynchronous Services, Easy as Synchronous RPC
Restate: Event-driven Asynchronous Services, Easy as Synchronous RPCRestate: Event-driven Asynchronous Services, Easy as Synchronous RPC
Restate: Event-driven Asynchronous Services, Easy as Synchronous RPC
HostedbyConfluent
 
Intention Oriented Model Interaction
Intention Oriented Model InteractionIntention Oriented Model Interaction
Intention Oriented Model Interaction
Yasir Karam
 

Similar to Concurrent programming with Agents (20)

Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stal
 
Architectural Patterns - Interactive and Event Handling Patterns
Architectural Patterns  - Interactive and Event Handling PatternsArchitectural Patterns  - Interactive and Event Handling Patterns
Architectural Patterns - Interactive and Event Handling Patterns
 
Web Services 8
Web Services 8Web Services 8
Web Services 8
 
IoT in salsa Serverless
IoT in salsa ServerlessIoT in salsa Serverless
IoT in salsa Serverless
 
Akka framework
Akka frameworkAkka framework
Akka framework
 
Delegates and events
Delegates and eventsDelegates and events
Delegates and events
 
Windows 8 BootCamp
Windows 8 BootCampWindows 8 BootCamp
Windows 8 BootCamp
 
Design patterns - ICIN 2010
Design patterns - ICIN 2010Design patterns - ICIN 2010
Design patterns - ICIN 2010
 
Event driven systems
Event driven systems Event driven systems
Event driven systems
 
Sysprog 10
Sysprog 10Sysprog 10
Sysprog 10
 
Sysprog 10
Sysprog 10Sysprog 10
Sysprog 10
 
Restate: Event-driven Asynchronous Services, Easy as Synchronous RPC
Restate: Event-driven Asynchronous Services, Easy as Synchronous RPCRestate: Event-driven Asynchronous Services, Easy as Synchronous RPC
Restate: Event-driven Asynchronous Services, Easy as Synchronous RPC
 
Design Pattern with Actionscript
Design Pattern with ActionscriptDesign Pattern with Actionscript
Design Pattern with Actionscript
 
Distributed System
Distributed System Distributed System
Distributed System
 
Android 101 Session @thejunction32
Android 101 Session @thejunction32Android 101 Session @thejunction32
Android 101 Session @thejunction32
 
Asynchronyin net
Asynchronyin netAsynchronyin net
Asynchronyin net
 
Distributed Objects and Remote Invocation
Distributed Objects and Remote InvocationDistributed Objects and Remote Invocation
Distributed Objects and Remote Invocation
 
Task communication
Task communicationTask communication
Task communication
 
Ddd melbourne 2011 C# async ctp
Ddd melbourne 2011  C# async ctpDdd melbourne 2011  C# async ctp
Ddd melbourne 2011 C# async ctp
 
Intention Oriented Model Interaction
Intention Oriented Model InteractionIntention Oriented Model Interaction
Intention Oriented Model Interaction
 

More from Tomas Petricek

Queries in general purpose languages
Queries in general purpose languagesQueries in general purpose languages
Queries in general purpose languages
Tomas Petricek
 

More from Tomas Petricek (19)

Coeffects: A Calculus of Context-Dependent Computation
Coeffects: A Calculus of Context-Dependent ComputationCoeffects: A Calculus of Context-Dependent Computation
Coeffects: A Calculus of Context-Dependent Computation
 
Domain Specific Languages: The Functional Way
Domain Specific Languages: The Functional WayDomain Specific Languages: The Functional Way
Domain Specific Languages: The Functional Way
 
F# Data: Making structured data first class citizens
F# Data: Making structured data first class citizensF# Data: Making structured data first class citizens
F# Data: Making structured data first class citizens
 
Doing data science with F# (BuildStuff)
Doing data science with F# (BuildStuff)Doing data science with F# (BuildStuff)
Doing data science with F# (BuildStuff)
 
Doing data science with F#
Doing data science with F#Doing data science with F#
Doing data science with F#
 
F# and Financial Data Making Data Analysis Simple
F# and Financial Data Making Data Analysis SimpleF# and Financial Data Making Data Analysis Simple
F# and Financial Data Making Data Analysis Simple
 
Creating Domain Specific Languages in F#
Creating Domain Specific Languages in F#Creating Domain Specific Languages in F#
Creating Domain Specific Languages in F#
 
How F# Learned to Stop Worrying and Love the Data
How F# Learned to Stop Worrying and Love the DataHow F# Learned to Stop Worrying and Love the Data
How F# Learned to Stop Worrying and Love the Data
 
Information-rich programming in F# (ML Workshop 2012)
Information-rich programming in F# (ML Workshop 2012)Information-rich programming in F# (ML Workshop 2012)
Information-rich programming in F# (ML Workshop 2012)
 
F# Type Providers in Depth
F# Type Providers in DepthF# Type Providers in Depth
F# Type Providers in Depth
 
Asynchronous programming in F# (QCon 2012)
Asynchronous programming in F# (QCon 2012)Asynchronous programming in F# (QCon 2012)
Asynchronous programming in F# (QCon 2012)
 
Queries in general purpose languages
Queries in general purpose languagesQueries in general purpose languages
Queries in general purpose languages
 
Docase notation for Haskell
Docase notation for HaskellDocase notation for Haskell
Docase notation for Haskell
 
Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#
 
F# on the Server-Side
F# on the Server-SideF# on the Server-Side
F# on the Server-Side
 
F# Tutorial @ QCon
F# Tutorial @ QConF# Tutorial @ QCon
F# Tutorial @ QCon
 
Teaching F#
Teaching F#Teaching F#
Teaching F#
 
F# in MonoDevelop
F# in MonoDevelopF# in MonoDevelop
F# in MonoDevelop
 
Academia
AcademiaAcademia
Academia
 

Recently uploaded

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Recently uploaded (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Concurrent programming with Agents

  • 1. Concurrent programming with Agents Tomáš Petříček http://tomasp.net/blog http://twitter.com/tomaspetricek
  • 2. Introducing agents Inside agent’s brain Inter-agent communication Reusable agents Intelligence networks
  • 6. Agent-based concurrency Programs compose from agents Instead of functions or objects Agents exchange messages Receive message and react Reactive system Handle inputs while running Emit results while running
  • 8. Functional loop with single state Single state Same reaction to all messages Implemented using recursive loop What if reaction depends on the state? What if agent cannot handle some message? Immutable state Maintained as parameter of recursive function Can use mutable collections for performance
  • 9. Hiding agent’s brain Accessing agent directly Exposes implementation details Users can call wrong methods (e.g. Receive) Encapsulating agent Agent as a private filed Add methods for all (public) messages Expose asynchronous calls first
  • 10. Example Encapsulating agent into an object Exposing chat room via HTTP
  • 11. Hiding agent’s brain  Asynchronous calls from F#  Synchronous calls from F# (optional)  Asynchronous calls from C# (task based) member x.AsyncGetContent(?timeout) = agent.PostAndAsyncReply(GetContent, ?timeout=timeout) member x.GetContent(?timeout) = agent.PostAndReply(GetContent, ?timeout=timeout) member x.GetContentAsync() = Async.StartAsTask(agent.PostAndAsyncReply(GetContent)) member x.GetContentAsync(cancellationToken) = Async.StartAsTask(agent.PostAndAsyncReply(GetContent), cancellationToken=cancellationToken)
  • 12. Introducing agents Inside agent’s brain Inter-agent communication Reusable agents Intelligence networks
  • 13. Inside agent’s brain Single state Accept and react to all messages Example: Twitter status agent with pause Resume Pause d Running Resume Status Pause Multiple states Agent implements a state machine
  • 14. Example Reading statuses from Twitter Pausing the stream using blocking agent
  • 15. State and state transitions Accepting all messages Asynchronously Receive and use pattern matching Waiting for specific message Other messages stay in the queue Writing message handling using Scan let rec state = agent.Scan(function | Message -> Some <| async { handleMessage() return! newState } | _ -> None )
  • 16. Introducing agents Inside agent’s brain Inter-agent communication Reusable agents Intelligence networks
  • 17. Inter-agent communication Direct links between agents Complicates reusability and reconfiguration Decoupling using events Expose event instead of sending message We used events in the previous example!
  • 18. Types of agent’s members Send message to the agent Members of type: 'T -> unit Notifications from the agent Exposed as events or observables: IObservable<'T> No synchronization and no thread guarantees Send and wait for a reply Uses asynchronous reply channels from F# library Takes arguments and returns result: 'T -> Async<'R>
  • 19. Connecting agents Sending message in response to notification Alternatively, Observable.subscribe supports removal Connecting agents with asynchronous actions Create and start asynchronous workflow source.Notification |> Observable.add target.Action async { while true do let! value = source.AsyncAction() do! target.Action(value) } |> Async.Start
  • 20. Introducing agents Inside agent’s brain Inter-agent communication Reusable agents Intelligence networks
  • 21. Reusable agents I. Aggregating messages into bulks Bulk specified number of messages Emit bulk after timeout Uses of bulking agent Grouping data for further processing Writing live data to a database new BulkingAgent : int -> int -> BulkingAgent member Enqueue : 'T -> unit member BulkProduced : Event<'T[]>
  • 22. Example Bulk processing of Twitter statuses A look at the BulkingAgent implementation
  • 23. Reusable agents II. Blocking queue with limited size Block reader when queue is empty Block adder when queue is full Uses of blocking queue agent The producer consumer pattern Immediate buffer in pipeline processing new BlockingQueueAgent : int -> BlockingQueueAgent member AsyncGet : unit -> Async<'T> member AsyncAdd : 'T -> Async<unit>
  • 24. Introducing agents Inside agent’s brain Inter-agent communication Reusable agents Intelligence networks
  • 25. Managing intelligence network  Lots of things going on! How to keep a big picture? Using loosely coupled connections Agents don’t reference each other directly Common ways of organizing agents Worker agent – Single agent does all the work Layered network – Agent uses agents from lower level Pipeline processing – Step-by-step processing
  • 26. Pipeline processing Values processed in multiple steps Worker takes value, processes it, and sends it Worker is blocked when source is empty Worker is blocked when target is full Steps of the pipeline run in parallel
  • 28. Summary Why use agent-based concurrency? Easy to understand reactive applications Elegant implementation of concurrent patterns How to write an agent-based application? State machine using recursive functions Encapsulate and provide communication points (send and send & reply methods and notifications) Use reusable agents for recurring patterns
  • 29. Questions? Email: tomas@tomasp.net Blog: http://tomasp.net/blog Twitter: http://twitter.com/tomaspetricek My book: http://functional-programming.net