C++ 多线程 : thread-safe memory allocation

标签 c++

我想了解在 C++11 中 new/delete 是否是线程安全的。 我发现了相互矛盾的答案。 我正在运行这个简短的程序,有时我从两个线程中得到不同的结果(我希望总是得到相同的结果)。 这是由于内存分配问题吗?我错过了什么? 我尝试使用 malloc/free,行为相同。

我正在编译它:

g++ -o out test_thread.cpp -std=c++11 -pthread
g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4

谢谢。

#include <string>
#include <iostream>
#include <thread>
#include <stdlib.h>

void task(int id)
{
    int N = 10000;
    srand(100);
    int j;
    long tot = 0;

    int *v = new int[N];
/*    int *v = 0;
    v = (int *) malloc (N * sizeof(int));
    */

    for (j = 0; j < N; j++)
        v[j] = rand();

    for (j = 0; j < N; j++)
        tot += v[j];

    //free(v);
    delete [] v;
    printf("Thread #%d: total %ld\n", id, tot);
}

int main()
{
    std::thread t1(task, 1);
    std::thread t2(task, 2);

    t1.join();
    t2.join();
}

最佳答案

rand() 在线程之间共享状态;这已经说明了您的观察结果。

关于C++ 多线程 : thread-safe memory allocation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46624193/

相关文章:

c++ - 编译器在使用 public bool 时提示 'QTransform::QTransform(bool)' 是私有(private)的,为什么?

c++ - 如何编译 Apache Avro C++ 示例

c++ - 为什么 std::hash 是结构而不是函数?

c++ - 多线程初级查询(C++)

c++ - 如何在类函数中创建线程?

c++ - 如何在 c++ win32 API 中向菜单项添加图标

c++ - 对 pthreads 感到困惑

c++ - 错误 : use of deleted function. 为什么?

c++ - C++ 中的 C# Dll,如何

c++ - 在 C++ 中创建多维数组棋盘的问题