14

I was wondering why reading from memory is not thread-safe. Among what I've seen so far, inter alia this question, reading from memory does not appear to be thread-safe.

I've been coding in Python for a while and now getting into C++. I've never heard that reading in Python is not thread-safe.

Please correct me if I'm wrong, but if not, please tell me why reading from memory is not thread-safe.

4

4 回答 4

20

Reading is thread safe, no problems..... until something writes to the location you're reading from, and then... well, hopefully you'll read before the data was changed, or read after the data was changed (in these cases, no worries), but sometimes, just when you really don't want it, you'll read half-way through the write and then you'll get compete garbage data.

The way to mitigate this is to ensure that you only read either before or after any writes, which requires you to check that a write is occurring and thus use a synchronisation lock of some sort. This makes things slower though, as you're obviously checking the lock and then reading instead of reading. If you're working with primitive data types (an int for example) then you can use a CPU synchronisation to speed this up dramatically.

As fr Python, chances are python data is always synchronised for you by the language runtime, if it isn't then you will get the same thread read problems sooner or later. (quick google says yes, Python will suffer the same problems is you're not careful)

于 2012-07-25T10:40:21.120 回答
9

It is thread safe if many threads are reading the same location, until no one attempts to write there.

Consider if thread A is reading something at the same time as thread B is writing at the memory being read. It will generate a race condition. The reading result can become invalid or different from launch to launch

于 2012-07-25T10:34:16.507 回答
9

Reading from memory is thread-safe, reading from memory that can be written to at the same time isn't safe though.

In Python this is less of a problem as a lot of objects are immutable, hence only references are modified in those cases, not the memory itself.

于 2012-07-25T10:35:51.097 回答
1

Reading the same thing simultaneously - is safe. The problem is when something writes to it at the same time.

Consider the following code:

int arr_len = 3;
int* arr = new int[arr_len];

void thread_1()
{
    std::cout << arr[arr_len-1];
}

void thread_2(int new_len)
{
    int* temp = new int[new_len];
    for(int i = 0; i < arr_len && i < new_len; ++i)
        temp[i] = arr[i];
    arr_len = new_len;
    delete arr;
    arr = temp;
}

Let's suppose that arr[arr_len] is done sequentially (first arr_len is read, and then arr).

What happens when the 2 threads run interleaved? One of three things can happen:

  • No problem - You're lucky!
  • arr_len is larger than arr - UB :(
  • arr is invalidated (was deleted) - UB :(
于 2016-07-07T18:14:52.857 回答