简体   繁体   中英

Reading and writing a variable at the same time

I have a program with multiple pthreads. These threads report data back to static variables through get and set functions in a common file.

static int LAT;
void getLat(){
    return LAT;
}
void setLAT(int lat){
    LAT = lat;
}

What will happen if one thread is executing getLAT(); and another is executing setLAT(); at the same time? Will my program crash? If so how can I prevent this?

This is called a race condition and results in undefined behavior. Anything could happen. A crash is unlikely, what's more likely is that the result could be that of before the write, after the write, or a corrupted in-the-middle-of-the-write value.

If you attempt to use that corrupted value in a system call or as a pointer offset, etc. would be a crash at that point.

Some platforms and architectures will guarantee atomic reads/writes for objects of a certain size aligned to a certain address (eg atomic 4 byte reads if aligned to a 16byte address, etc.), in which case the intermediate value (corrupt) will not happen. But you can't really rely on that behavior as it isn't portable. And even when that behavior isn't guaranteed, your code will likely run fine 99% of the time, except for that one percent in production when you'll wish you hadn't taken the shortcut and not bothered with synchronization.

You need to use a mutex or a atomic read/write instruction like cmpxchg to protect your code from this race condition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM