Question

Think of a network of nodes (update: 'network of nodes' meaning objects in the same application domain, not a network of independent applications) passing objects to each other (and doing some processing on them). Is there a pattern in C# for restricting the access to an object to only the node that is actually processing it?

Main motivation: Ensuring thread-safety (no concurrent access) and object consistency (regarding the data stored in it).

V1: I thought of something like this:

class TransferredObject
    {
        public class AuthLock
        {
            public bool AllowOwnerChange { get; private set; }
            public void Unlock() { AllowOwnerChange = true; }
        }

        private AuthLock currentOwner;

        public AuthLock Own()
        {
            if (currentOwner != null && !currentOwner.AllowOwnerChange)
                throw new Exception("Cannot change owner, current lock is not released.");

            return currentOwner = new AuthLock();
        }

        public void DoSomething(AuthLock authentification)
        {
            if (currentOwner != authentification)
                throw new Exception("Don't you dare!");

            // be sure, that this is only executed by the one holding the lock

            // Do something...
        }
    }

    class ProcessingNode
    {
        public void UseTheObject(TransferredObject  x)
        {
            // take ownership
            var auth = x.Own();

            // do processing
            x.DoSomething(auth);

            // release ownership
            auth.Unlock();
        }
    }

V2: Pretty much overhead - a less 'strict' implementation would perhaps be to ignore the checking and rely on the "lock/unlock" logic:

class TransferredObject
    {
        private bool isLocked;

        public Lock() 
        {
            if(isLocked)
                throw new Exception("Cannot lock, object is already locked.");

            isLocked = true; 
        }
        public Unlock() { isLocked = false; }

        public void DoSomething()
        {
            if (isLocked)
                throw new Exception("Don't you dare!");

            // Do something...
        }
    }

    class ProcessingNode
    {
        public void UseTheObject(TransferredObject  x)
        {
            // take ownership
            x.Lock = true;

            // do processing
            x.DoSomething();

            // release ownership
            x.Unlock = true;
        }
    }

However: This looks a bit unintuitive (and having to pass an the auth instance with ervery call is ugly). Is there a better approach? Or is this a problem 'made by design'?

Was it helpful?

Solution

To clarify your question: you seek to implement the rental threading model in C#. A brief explanation of different ways to handle concurrent access to an object would likely be helpful.

  • Single-threaded: all accesses to the object must happen on the main thread.

  • Free-threaded: any access to the object may happen on any thread; the developer of the object is responsible for ensuring the internal consistency of the object. The developer of the code consuming the object is responsible for ensuring that "external consistency" is maintained. (For example, a free-threaded dictionary must maintain its internal state consistently when adds and removes happen on multiple threads. An external caller must recognize that the answer to the question "do you contain this key?" might change due to an edit from another thread.)

  • Apartment threaded: all accesses to a given instance of an object must happen on the thread that created the object, but different instances can be affinitized to different threads. The developer of the object must ensure that internal state which is shared between objects is safe for multithreaded access but state which is associated with a given instance will only ever be read or written from a single thread. Typically UI controls are apartment threaded and must be in the apartment of the UI thread.

  • Rental threaded: access to a given instance of an object must happen from only a single thread at any one time, but which thread that is may change over time

So now let's consider some questions that you should be asking:

  • Is the rental model a reasonable way to simplify my life, as the author of an object?

Possibly.

The point of the rental model is to achieve some of the benefits of multithreading without taking on the cost of implementing and testing a free-threaded model. Whether those increased benefits and lowered costs are a good fit, I don't know. I personally am skeptical of the value of shared memory in multithreaded situations; I think the whole thing is a bad idea. But if you're bought into the crazy idea that multiple threads of control in one program modifying shared memory is goodness, then maybe the rental model is for you.

The code you are writing is essentially an aid to the caller of your object to make it easier for the caller to obey the rules of the rental model and easier to debug the problem when they stray. By providing that aid to them you lower their costs, at some moderate increase to your own costs.

The idea of implementing such an aid is a good one. The original implementations of VBScript and JScript at Microsoft back in the 1990s used a variation on the apartment model, whereby a script engine would transit from a free-threaded mode into an apartment-threaded mode. We wrote a lot of code to detect callers that were violating the rules of our model and produce errors immediately, rather than allowing the violation to produce undefined behaviour at some unspecified point in the future.

  • Is my code correct?

No. It's not threadsafe! The code that enforces the rental model and detects violations of it cannot itself assume that the caller is correctly using the rental model! You need to introduce memory barriers to ensure that the various threads reading and writing your lock bools are not moving those reads and writes around in time. Your Own method is chock full of race conditions. This code needs to be very, very carefully designed and reviewed by an expert.

My recommendation - assuming again that you wish to pursue a shared memory multithreaded solution at all - is to eliminate the redundant bool; if the object is unowned then the owner should be null. I don't usually advocate a low-lock solution, but in this case you might consider looking at Interlocked.CompareExchange to do an atomic compare-and-swap on the field with a new owner. If the compare to null fails then the user of your API has a race condition which violates the rental model. This introduces a memory barrier.

OTHER TIPS

Maybe your example is too simplified and you really need this complex ownership thing, but the following code should do the job:

class TransferredObject
{
    private object _lockObject = new object();

    public void DoSomething()
    {
        lock(_lockObject)
        {
            // TODO: your code here...
        }
    }
}

Your TransferredObject has an atomic method DoSomething that changes some state(s) and should not run multiple times at the same time. So, just put a lock into it to synchronize the critical section.

See http://msdn.microsoft.com/en-us/library/c5kehkcz%28v=vs.90%29.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top