簡體   English   中英

C ++多線程:線程安全的內存分配

[英]C++ multi-threading: thread-safe memory allocation

我試圖了解在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()在線程之間共享狀態; 已經說明了您的意見。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM