Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 542
user338421 Avatar asked Sep 21 '25 00:09

user338421


2 Answers

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

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

like image 92
Oded Avatar answered Sep 22 '25 13:09

Oded


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.

like image 30
dcp Avatar answered Sep 22 '25 14:09

dcp