Do I need a lock when only a single thread writes

2019-02-06 16:03发布

I have 2 threads and a shared float global. One thread only writes to the variable while the other only reads from it, do I need to lock access to this variable? In other words:

volatile float x;

void reader_thread() {
    while (1) {
        // Grab mutex here?
        float local_x = x;
        // Release mutex?
        do_stuff_with_value(local_x);
    }
}

void writer_thread() {
    while (1) {
        float local_x = get_new_value_from_somewhere();
        // Grab mutex here?
        x = local_x;
        // Release mutex?
    }
}

My main concern is that a load or store of a float not being atomic, such that local_x in reader_thread ends up having a bogus, partially updated value.

  1. Is this a valid concern?
  2. Is there another way to guarantee atomicity without a mutex?
  3. Would using sig_atomic_t as the shared variable work, assuming it has enough bits for my purposes?

The language in question is C using pthreads.

7条回答
趁早两清
2楼-- · 2019-02-06 16:38

Since it's a single word in memory you're changing you should be fine with just the volatile declaration.

I don't think you guarantee you'll have the latest value when you read it though, unless you use a lock.

查看更多
登录 后发表回答