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
Shared resources that are accessed by multiple threads need to be synchronized.
Since arrays are not thread safe, you need to manage this yourself.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With