0

Facebook の友達データのベクトルを含むクラスがあります。

std::vector<FBFriend> m_friends

FB は非常に単純な構造体です。

struct FBFriend
{
    std::string ID;
    std::string photoPath;
    std::string name;
    bool installed;
    int score;
};

FB から (非同期スレッドで) データをダウンロードするとき、m_friends フィールドを反復処理して、対応する画像を割り当てますが、不正なアクセス エラーが発生します。

何か案が?

ありがとう。

4

1 に答える 1

0

複数のスレッドから変数にアクセスする場合、データの競合を避けるために、読み取りと書き込みを同期する必要があります。

std::mutexと を使用してアクセスを同期する方法の簡単な例を次に示しますstd::lock_guard

std::mutex m;
std::vector<FBFriend> v;

// Add two FBFriend to vector.
v.push_back({"user1", "/photos/steve", "Steve", true, 0});
v.push_back({"user2", "/photos/laura", "Laura", true, 0});

// Change element in vector from a different thread.
auto f = std::async(std::launch::async, [&] {
    std::lock_guard<std::mutex> lock(m); // Aquire lock before writing.
    v[0].photoPath = "/images/steve";
});

f.wait(); // Wait for task to finish.

std::cout << v[0].photoPath << std::endl;
std::cout << v[1].photoPath << std::endl;

出力:

/images/steve
/photos/laura
于 2013-08-13T12:32:09.730 に答える