In C++11, I create threads with std::thread
. And I have some global variables:
const int max_size = 78;
const int cat[5] = {1, 20, 3, 40, 5};
Now, if my threads read those variables, is there any chance of unidentified behavior?
In C++11, I create threads with std::thread
. And I have some global variables:
const int max_size = 78;
const int cat[5] = {1, 20, 3, 40, 5};
Now, if my threads read those variables, is there any chance of unidentified behavior?
As long as those variables are never written to (yes it is possible to write to const
variables in C++ via pointer manipulation, but for what reason?) then no.
If you are worried about undefined or unspecified behavior (with respect to thread safety), you could always use a mutex.
An OK example:
// Globals
const int max_size = 78;
const int cat[5] = {1, 20, 3, 40, 5};
void call_from_thread() {
std::cout << "Max Size: " << max_size << std::endl;
std::cout << "cat[0]: " << cat[0] << std::endl;
//..
std::cout << "cat[4]: " << cat[4] << std::endl;
}
int main() {
//Launch some threads
std::thread thread1(call_from_thread);
std::thread thread2(call_from_thread);
//Join the threads with the main thread
thread1.join();
thread2.join();
//..
*((int*)&cat[3])=15; // Since threads are joined, this is OK as far as the write is concerned
return 0;
}
In the above example, writing to a const
variable can cause undefined behavior. So it is still a REALLY BAD idea.
A really really bad example:
int main() {
//Launch some threads
std::thread thread1(call_from_thread);
std::thread thread2(call_from_thread);
*((int*)&cat[3])=15; // BAD idea for thread safety as well as what is discussed above.
//Join the threads with the main thread
thread1.join();
thread2.join();
//..
return 0;
}