apocalypse
apocalypse

Reputation: 5884

Shared object and threads

I designed a class MemoryBlock. Like the name says it's a block of (unmanaged) memory. I just simply do var x = new MemoryBlock (1024, 16) and it gives me 1kB of memory (also aligned to 16 bytes). So now some threads want to read/write to this block using unsafe context. I did something like SyncRoot property to synchronize threads. So I do lock (myMemoryBlock.SyncRoot) and do some stuff with the memory. I don't know it's good or not, but I saw something like this in colletions.
This simple mechanism do not allow more than one thread to access this object. It's OK for writing but not enought for reading. I want something like this:

1) if thread is writing to object, no other thread can access this object
2) if thread is reading from object, many other threads can read from this object, but cannot write to it
3) if object is used and thread want to write, thread waits until object is free
4) expert mode: if some threads are reading from object, and another thread want to write to it, it waits until object is free but also tells object to stop gives access to new thread which want to read from this object (queue).

I will be very glad for simple tips, not need a code.

Upvotes: 3

Views: 1416

Answers (2)

Sergii Vashchyshchuk
Sergii Vashchyshchuk

Reputation: 970

You should use a ReaderWriterLockSlim.

Here is the common usage of this class:

public class SomeClass
{
    private MemoryBlock block = new MemoryBlock(1024, 16);

    private ReaderWriterLockSlim blockSyncObjcect = new ReaderWriterLockSlim();

    public void SomeRead()
    {
        blockSyncObjcect.EnterReadLock();

        // Safe reading from the block

        blockSyncObjcect.ExitReadLock();
    }

    public void SomeWrite()
    {
        blockSyncObjcect.EnterWriteLock();

        // Safe writing to the block

        blockSyncObjcect.ExitWriteLock();
    }
}

Upvotes: 1

itadapter DKh
itadapter DKh

Reputation: 590

Look at ReaderWriterLockSlim. Basically it benefits any case where many readers need to read concurrently but any writer shall block all readers. If you have read/write ratio of 50:50 then use regular lock(obj){}

Example: ReadWriteLockSlim is good for caching i.e. many readers per second but cache updates once every 5 minutes.

http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx

Upvotes: 1

Related Questions