在 C++11 中,我使用 std::thread
创建线程。我有一些全局变量:
const int max_size = 78;
const int cat[5] = {1, 20, 3, 40, 5};
现在,如果我的线程读取这些变量,是否有可能出现未识别的行为?
最佳答案
只要这些变量永远不会被写入(是的,可以通过指针操作在 C++ 中写入 const
变量,但出于什么原因?)那么就不会。
如果您担心未定义或未指定的行为(关于线程安全),您总是可以使用互斥体。
一个好的例子:
// 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;
}
在上面的示例中,写入 const
变量可能会导致未定义的行为。所以这仍然是一个非常糟糕的主意。
一个非常糟糕的例子:
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;
}
关于C++ 常量安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21031747/