Using an array with multiple read streams + write

I am not sure about that.

Using the array int []. If in my application stream A reads when stream B is written to the same array element, will everything be saved?

I would also prefer not to synchronize the block when reading - this is used in the web service, so I will not serve several clients in parallel.

Thank.

Olivie

+3
source share
5 answers

No, you need to use a blocking block so that no one tries to read the array while some other process writes to it. Otherwise, you may 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];
    }
}

, , . .

+1

, , ReaderWriterLockSlim ( , , .)

, , . , , , , , - - . .

+1

, .

, .

0

Arrays are not thread safe when reading and writing in streaming media: http://msdn.microsoft.com/en-us/library/system.array.aspx

You will need to block the array, t1.Join (); t2.Join () may work, although I'm not sure.

0
source

You need to block access to your array from multiple parallel threads. The easiest way is to allow access to your array using getters / seters, and then paste some lock code into it.

0
source

Source: https://habr.com/ru/post/1759125/


All Articles