C++多线程:线程安全的内存分配

C++ multi-threading: thread-safe memory allocation

本文关键字:内存 分配 安全 线程 多线程 C++      更新时间:2023-10-16

我试图了解在 C++11 中新建/删除是否是线程安全的。我发现了相互矛盾的答案。我正在运行这个简短的程序,有时我从两个线程中得到不同的结果(我希望总是得到相同的结果)。这是由于内存分配问题造成的吗?我错过了什么?我尝试使用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 %ldn", id, tot);
}
int main()
{
    std::thread t1(task, 1);
    std::thread t2(task, 2);
    t1.join();
    t2.join();
}
rand()线程

之间共享状态;这已经解释了你的观察结果。