Skip to content

Instantly share code, notes, and snippets.

@JohnNilsson
Forked from viktorklang/Actor.java
Created May 6, 2012 22:17
Show Gist options
  • Save JohnNilsson/2624807 to your computer and use it in GitHub Desktop.
Save JohnNilsson/2624807 to your computer and use it in GitHub Desktop.
Minimalist C# Actors
// 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);
}
}
}
@viktorklang
Copy link

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.

@JohnNilsson
Copy link
Author

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.

@JohnNilsson
Copy link
Author

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...

@viktorklang
Copy link

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