Gizmo
Gizmo

Reputation: 2210

Reading dynamic/changing data from multiple threads without locks? Can it cause a crash? Or just corrupted variables?

Suppose I'm the best uber hacker in the world and I need to monitor a programs behaviour,

I do this by creating a dynamic library or program which creates a few threads and then just reads bytes from the memory (via raw pointers or any other direct memory getting model without functions). This "should" be safe? As the only thing you can get is just a malformed variable (eg writing is done when you read)? then just ignore it and read again?

I always see documents takling about race conditions, deadlocks and other issues related to multithreading. But they are not always as clear as I would like them to be and I'm left with unanswered questions.

If a thread writes to a piece of memory, and other threads, like 3-4, constantly read the memory (suppose a non-std::atomic int or float) and perform some thread-scoped operations with it (like calculating the speed of a given x,y,z vector), then this program would run safely and there will be defined behaviour, or will there be UB, or maybe an application crash at some point? (maybe multiplication of malformed float bytes can cause a crash?)

And if it's not safe, is there a way to "safely" get the memory contents from a piece of memory from a few threads without having access to the target program internals?

Upvotes: 0

Views: 1497

Answers (2)

Jerry Coffin
Jerry Coffin

Reputation: 490028

Do you care primarily about the official C++ answer, or the practical answer?

The official C++ answer is that simultaneous reading and writing without locking can/will lead to a race condition, which gives undefined behavior -- anything could happen.

The more practical answer is that with any decently designed CPU, about the worst that will happen is that you'll get an incorrect value. It's a bug for your code to attempt to read the data without a lock, but it's (at least) equally a bug on the part of the CPU if it lets anything terrible happen because two threads had conflicting reads/writes. If writing the variable isn't atomic, it's perfectly permissible for you to get a partially written value -- but crashing the machine or something like that would be a major bug on the part of the CPU.

Upvotes: 2

Alok Save
Alok Save

Reputation: 206508

Reading and writing to same data objects from multiple threads gives you Undefined Behavior and Undefined behavior does not mandate a crash, it simply means that the program can show any behavior. Simply put you cannot rely on the behavior to be consistent because it is simply not mandated as per the standard.

The only safe way to access such a object will be to ensure:

  • Atomic & synchronized accesses through locks

Upvotes: 2

Related Questions