Medium
Lazy-loading proxy shared by two reader threads
Both threads call size() on the same const proxy, and neither call has happened before. What is the behavior of this program?
main.cpp
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>
struct Image {
explicit Image(const std::string& path) { pixels.resize(1 << 20); } // expensive decode
std::vector<unsigned char> pixels;
};
class ImageProxy {
public:
explicit ImageProxy(std::string path) : path_(std::move(path)) {}
std::size_t size() const {
if (!real_) real_ = std::make_unique<Image>(path_); // load on first use
return real_->pixels.size();
}
private:
std::string path_;
mutable std::unique_ptr<Image> real_;
};
int main() {
const ImageProxy proxy("hero.png");
std::thread a([&] { std::cout << proxy.size() << "\n"; });
std::thread b([&] { std::cout << proxy.size() << "\n"; });
a.join();
b.join();
}32 of 44 in Design Patterns