21
std::shared_ptr<int> g_s = std::make_shared<int>(1);
void f1()
{
    std::shared_ptr<int>l_s1 = g_s; // read g_s
}

void f2()
{
    std::shared_ptr<int> l_s2 = std::make_shared<int>(3);
    std::thread th(f1);
    th.detach();
    g_s = l_s2; // write g_s
}

上記のコードに関して、異なるスレッドが同じ読み取りと書き込みを行うとshared_ptr、競合状態が発生することがわかっています。しかし、どうweak_ptrですか?以下のコードに競合状態はありますか? (私のプラットフォームは Microsoft VS2013 です。)

std::weak_ptr<int> g_w;

void f3()
{
    std::shared_ptr<int>l_s3 = g_w.lock(); //2. here will read g_w
    if (l_s3)
    {
        ;/.....
    }
}

void f4()
{
    std::shared_ptr<int> p_s = std::make_shared<int>(1);
    g_w = p_s;

    std::thread th(f3);
    th.detach();
    // 1. p_s destory will motify g_w (write g_w)
}
4

5 に答える 5

5

shared_ptrまた、weak_ptr他のすべての標準ライブラリ タイプと同じブランケット スレッド セーフ要件に該当します。メンバー関数が非変更の場合、メンバー関数への同時呼び出しはスレッド セーフでなければなりません ( const) (詳細は C++11 §17.6.5.9 データ競合回避 [res. data.races])。代入演算子は特にそうではありません const

于 2013-12-20T15:18:47.130 に答える