-
-
Save JohnNilsson/2624807 to your computer and use it in GitHub Desktop.
Minimalist C# Actors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Inspired by https://gist.github.com/2557678 | |
// and http://dspace.mit.edu/bitstream/handle/1721.1/6935/AITR-633.pdf | |
using System; | |
using System.Collections.Concurrent; | |
using System.Collections.Generic; | |
using System.Threading.Tasks.Dataflow; | |
using Message = System.Object; | |
namespace Actors | |
{ | |
public interface Behavior { Behavior OnArrival(Message message); } | |
public class Actor | |
{ | |
private volatile Behavior behavior; | |
private readonly ActionBlock<Message> arrivals; | |
public Actor(Behavior initialBehavior) | |
{ | |
this.behavior = initialBehavior; | |
this.arrivals = new ActionBlock<Message>(message => { this.behavior = this.behavior.OnArrival(message); }); | |
} | |
public void Send(Message message) | |
{ | |
this.arrivals.SendAsync(message); | |
} | |
} | |
} |
hmm, can't seem to find any definitive documentation on this. lock introduces memory barriers but it is not clear if reading the monitor is safe. Official documentation contains example code that should exhibit the same issue though so I guess it should be safe.
Couldn't trigger the issue in a unit test either (4 core Intel I7)
Did determine that the Task-scheduling was roughly 1-2 magnitudes slower than ConcurrentQueue.Enque though...
You'll have to unsafely publish the reference to the newly allocated Actor and have the thread that picks it up send it a message.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My point is that if there's no mfence after the constructor, and the reference to the newly created Actor instance is done unsafely (i.e. w/o proper fencing) any other entity sending a method to it might see the original value of the lastEvent field, which will be null, and so the lock on null will barf.