C++ 常量安全

标签 c++ multithreading c++11

在 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/

相关文章:

c++ - 混合使用纯虚方法和虚方法的类

c++ - new 在堆栈而不是堆上(如 alloca 与 malloc)

c++ - 是否可以初始化具有相同名称但末尾数字不同的变量?

c++ - 多线程:写入后先从另一个线程访问...我需要volatile吗?

multithreading - 多线程环境中的单例

c++ - 为什么需要重新定义固定大小的静态数组/有效?

winforms - BackgroundWorker.ReportProgress() 和 Control.BeginInvoke() 之间的区别

c++ - std::make_unique SFINAE 友好吗?

c++ - "new int[];"是做什么的?

c++ - 调整 std::vector 的大小是否可能会降低其容量?