C++多线程:线程安全的内存分配
C++ multi-threading: thread-safe memory allocation
我试图了解在 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()
线程之间共享状态;这已经解释了你的观察结果。
相关文章:
- Win32编译器选项和内存分配
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 当需要超过16GB的连续内存时,内存分配失败
- 尝试摆脱任何堆内存分配
- 以下代码执行哪种内存分配(动态或静态)?
- 开放 CV 中的动态内存分配,用于视频处理
- 为什么类和 main() 函数中也有动态内存分配
- 使用 NTAllocateVirtualMemory 和 GetProcAddress 的内存分配问题不起作用
- C++:矢量分配器行为、内存分配和智能指针
- 介于 [固定数组] 和 [带内存分配的指针] 之间的性能
- Linux C++ 中的页面对齐内存分配
- 整数内存分配/释放
- 将内存分配返回值强制转换为 TYPE 数组
- C++程序什么都不做,但瓦尔格林德显示内存分配
- 给定特定内存地址的数组的动态内存分配
- 如何完成内存分配
- 我刚刚了解了C++中的动态内存分配
- 在先前调用 string::find 后添加内存分配和内存集会导致它返回 npos.为什么?
- 对于堆上的页面对齐内存分配是否有任何优化或不同的 API?
- 无法删除布尔动态内存分配