我想了解在 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/