2

I want to implement the famous reader writer model using actor model. We can have multiple reader reading but only one writer can write. Also when a writer writes no reader can read and vice versa.

To solve this problem i thought of using a superviser actor which maintains a set for reader actors and a queue for writer actors. Now a writer can be dequeued and start writing when the set for readers are empty. Also when the writer completes all reader actors from the set can start reading.

Can we have a better problem of solving this famous problem using actor model?

Also is this model better than the original reader writer problem soved using read or write locks?

kliew
  • 3,073
  • 1
  • 14
  • 25
Neel Choudhury
  • 573
  • 1
  • 5
  • 11

2 Answers2

2

You may want to look into "software transactional memory" with ScalaSTM libs.

You would create a shared Ref with atomic access. When multiple threads enter an atomic block, both proceed. The first thread to write to the Ref wins, and the loser restarts the atomic block (and thus re-reads) from the beginning. Thus, both threads will always work with up-to-date data.

https://nbronson.github.io/scala-stm/

STM is an alternative to Locks and Mutexes, but has better concurrency as it uses optimistic non-blocking writes as opposed to blocking on both writes and reads. It is also easier to write and maintain STM code than to do so with locks.

kliew
  • 3,073
  • 1
  • 14
  • 25
  • Thanks!! i will look into it. Also is there a way for this kind of problem using Actor model as it is heavily used in other part of my project – Neel Choudhury Mar 17 '16 at 18:34
  • Yes, STM can be used in conjunction with Actors. You'd create a singleton Ref encapsulating your shared object, and actors would access the data atomically. – kliew Mar 17 '16 at 23:43
  • Does it use `scala.blocking`? Will it cause spawning additional threads while actors wait on barrier? See http://stackoverflow.com/a/31110111/1387612 – janisz Dec 02 '16 at 10:19
0

You can simply create a supervisor actor to manage incoming requests. The supervisor Actor can then send messages to reader Actors. When the readers send the acknowledgment back write request can be forward to writer Actors.

Avi Chalbani
  • 842
  • 7
  • 11