Actually, this question seems to have two parts:
- How to implement pattern matching?
- How to implement send and receive (i.e. the Actor model)?
For the pattern matching part, I’ve been looking into various projects like App and Prop. These look pretty nice, but couldn’t get them to work on a recent version (4.x) of g++. The Felix language also seems to support pattern matching pretty well, but isn’t really C++.
As for the Actor model, there are existing implementations like ACT++ and Theron, but I couldn’t find anything but papers on the former, and the latter is single-threaded only [see answers].
Personally, I’ve implemented actors using threading and a thread-safe message queue. Messages are hash-like structures, and used these together with a number of preprocessor macros to implemented simple pattern matching.
Right now, I can use the following code to send a message:
(new Message(this)) ->set('foo', 'bar') ->set('baz', 123) ->send(recipient);
And the following to do simple pattern matching (qDebug and qPrintable are Qt-specific):
receive_and_match(m) match_key('foo') { qDebug('foo: %s', qPrintable(m->value('foo').toString())); } or_match_key('baz') { qDebug('baz: %d', m->value('baz').toInt()); } or_match_ignore end_receive
However, this looks a bit hackish to me, and isn’t very robust.
How would you do it? Did I miss any existing work?
One of the important things about erlang is how the features are used to make robust systems.
The send/recieve model is no-sharing, and explicitly copying. The processes themselves are lightweight threads.
If you did desire the robust properties of the erlang model, you would be best to use real processes and IPC rather than threads.
If you want robust message passing though you may end up wanting to serialize and deserialise the contents. Especially with type safety.
Pattern matching in C++ isn’t always pretty but there will be a good pattern for this – you will end up creating a dispatcher object that uses some form of polymorphism to get what you want.
Although if you are not careful you end up with xml over pipes 🙂
Really, if you want the erlang model you really want to use erlang. If there are slow bits, I’m sure you can augment your program using a foreign function internet.
The problem about re-implementing parts, is you won’t get a good cohesive library and solution. The solutions you have already don’t look much like C++ anymore.