user338421
user338421

Reputation: 91

Using Array with multiple reader threads + writer

I am no sure about this ..

Using an int[] array. If in my application, a thread A reads while a thread B writes into the same array element, will everything hold ?

I'd rather not have a synchronized block on reading also - this is used in a web service, so I won't be able to service multiple clients in parallel.

Thanks.

Olivier

Upvotes: 4

Views: 1346

Answers (5)

Drew Noakes
Drew Noakes

Reputation: 311345

If you're doing more reading than writing, then use ReaderWriterLockSlim to improve performance (though it will probably make your code more verbose.)

If you're worried about blocking your client threads then perhaps you can queue these operations into a threadsafe queue. Honestly though unless you're taking multiple locks for each request, you're unlikely to have to wait long enough on entry to these locks for a human user of your website to notice. This kind of performance impact is more significant when dealing with high throughput with low latency.

Upvotes: 1

dcp
dcp

Reputation: 55467

No, you need to use a lock block to ensure that no one is trying to read the array while some other process is writing to it. Otherwise, you are likely to have problems.

This is actually quite simple in C#, you can just do this:

// declare an object to use for locking
Object lockObj = new Object();

// declare the array
int[] x = new int[5];

// set the array value (thread safe operation)
public void SetArrayVal(int ndx, int val)
{
    if (ndx < 0 || ndx >= x.Length)
    {
        throw new ArgumentException("ndx was out of range", ndx);
    }    
    lock (lockObj )
    {
        x[ndx] = val;
    }
}

// get the array value (thread safe operation)
public int GetVal(int ndx)
{
    if (ndx < 0 || ndx >= x.Length)
    {
        throw new ArgumentException("ndx was out of range", ndx);
    }    
    lock (lockObj )
    {
        return x[ndx];
    }
}

I wouldn't worry so much about the performance here as to making sure you get the thread saftiness correct, which is critical.

Upvotes: 1

NeilDurant
NeilDurant

Reputation: 2132

You'll need to lock access to your array from multiple concurrent threads. The easiest way is to only allow access to your array using getters/setters, and then put some locking code into those.

Upvotes: 0

Brian
Brian

Reputation: 163

Arrays are not thread safe during reading and writing in threaded environments: http://msdn.microsoft.com/en-us/library/system.array.aspx

You would have to lock the array, a t1.Join(); t2.Join() might work as well although I'm not sure.

Upvotes: 0

Oded
Oded

Reputation: 499382

Shared resources that are accessed by multiple threads need to be synchronized.

Since arrays are not thread safe, you need to manage this yourself.

Upvotes: 1

Related Questions