Is it necessary to lock an array that is *only written to* from one thread and *only read from* another?

前端 未结 10 1517
后悔当初
后悔当初 2020-12-13 19:26

I have two threads running. They share an array. One of the threads adds new elements to the array (and removes them) and the other uses this array (read operations only).

10条回答
  •  长情又很酷
    2020-12-13 20:19

    One of the threads adds new elements to the array [...] and the other [reads] this array

    In order to add and remove elements to/from an array, you will need an index that specifies the last place of the array where the valid data is stored. Such index is necessary, because arrays cannot be resized without potential reallocation (which is a different story altogether). You may also need a second index to mark the initial location from which the reading is allowed.

    If you have an index or two like this, and assuming that you never re-allocate the array, it is not necessary to lock when you write to the array itself, as long as you lock the writes of valid indexes.

    int lastValid = 0;
    int shared[MAX];
    ...
    int count = toAddCount;
    // Add the new data
    for (int i = lastValid ; count != 0 ; count--, i++) {
        shared[i] = new_data(...);
    }
    // Lock a mutex before modifying lastValid
    // You need to use the same mutex to protect the read of lastValid variable
    lock_mutex(lastValid_mutex);
    lastValid += toAddCount;
    unlock_mutex(lastValid_mutex);
    

    The reason this works is that when you perform writes to shared[] outside the locked region, the reader does not "look" past the lastValid index. Once the writing is complete, you lock the mutex, which normally causes a flush of the CPU cache, so the writes to shared[] would be complete before the reader is allowed to see the data.

提交回复
热议问题