Programming: Concurrency Patterns: Difference between revisions
From wikinotes
Line 25: | Line 25: | ||
= Active Object = | = Active Object = | ||
<blockquote> | <blockquote> | ||
Safely share an object between threads,<br> | |||
each method call on a proxy-object triggers an execution in a separate thread.<br> | |||
Hides the lock/queue logic from the caller. | |||
ex. update a progressbar in the UI thread from a background thread | |||
* | * Background thread instantiates a proxy object | ||
* On a method call, the proxy returns a Future/Promise | * On a method call, the proxy returns a Future/Promise (a request is enqueued to UI thread) | ||
* | * The UI thread eventually performs the task | ||
* You may wait/join on the Future/Promise to wait for it to return it's results | * You may wait/join on the Future/Promise to wait for it to return it's results | ||
</blockquote><!-- Active Object --> | </blockquote><!-- Active Object --> |
Revision as of 03:36, 7 August 2022
Resources
Wikipedia: Concurrency Patterns https://en.wikipedia.org/wiki/Concurrency_pattern
Monitor Object
Safely share an object between multiple threads,
automatically wait in caller until a perform is done.
The caller does not need to know about the perform-lock, it will simply block until the monitor is able to process a new task.Say we only ever want to perform IO from one thread.
We create a WriterMonitor, which might have methods read/write
- in thread-1, we call read(), which blocks while in the background creates and performs a thread
- in thread-2, we call write(), it will block until it is notified that thread-1's read() is finished
Active Object
Safely share an object between threads,
each method call on a proxy-object triggers an execution in a separate thread.
Hides the lock/queue logic from the caller.ex. update a progressbar in the UI thread from a background thread
- Background thread instantiates a proxy object
- On a method call, the proxy returns a Future/Promise (a request is enqueued to UI thread)
- The UI thread eventually performs the task
- You may wait/join on the Future/Promise to wait for it to return it's results
Producer/Consumer
Safely parallelized task enqueueing/execution.
- A producer adds data to a synchronized queue
- A variable number of consumers process data from a synchronized queue in a loop
- When producer is finished, send a poison pill for each worker, informing it to break/exit the loop gracefully
- Join on worker threads (wait to close)