从多个线程访问变量时,必须同步读取和写入以避免数据竞争。
这是一个简单的示例,说明如何使用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