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