Will there be an application error if two threads read the same variable?
No, you can safely read the global variable at the same time (if you know that no one writes it at the same time). The read operation does not change the global value, therefore it remains unchanged, and all readers "see" the same value.
Or will an application crash only if one thread writes to a variable that another thread reads?
As a rule, no, at least not because of the simultaneous read and write operations. Crashing can be a side effect. For example, if you update a pointer value and read it at the same time, you are trying to access the data that the pointer points to. If the reading value is not valid, most likely you will crash.
in addition: this part
// ... if (value == "") { m.unlock(); return var; } // ...
also save stream?
No. Your mutex m only protects the local variable value , which does not need to be protected, since it is local. But then you release the mutex and copy ( read ) the global variable var , while another thread can write it. To make it thread safe, use std::lock_guard and you won’t need to manually lock / unlock mutexes. or update the code:
m.lock(); if (value == "") { string ret_val(var); m.unlock(); return ret_val; }
I do not use mutexes for my global variables. Maybe this “situation” may cause the application to crash
As I wrote earlier, yes, as a side effect, the application may crash.
source share