An image program used to process each image immediately after loading it. It now loads a batch first, records each image’s work as a Task in a queue, and processes the tasks after loading finishes. A Task’s name is the image filename, and pixels locates the pixels to process.
The program provides these two functions:
void load_image(const std::string& path, std::vector<int>& pixels);
void process(const std::string& name, const std::vector<int>& pixels);load_image reads the image at path into the supplied vector, replacing its previous contents; it does not keep using that vector after returning. process processes the supplied pixels and labels the result with name; it does not modify the pixels.
The queue, Task, and calling code are below. paths contains the filenames to process. The outer pixels object remains alive until all processing finishes.
template<class T>
class Queue {
std::deque<T> items_;
public:
void push(const T& item) { items_.push_back(item); }
T pop() { // called only when nonempty
T result = items_.front();
items_.pop_front();
return result;
}
bool empty() const { return items_.empty(); }
};
struct Task {
std::string name;
const std::vector<int>* pixels;
};std::vector<int> pixels;
Queue<Task> pending;
for (const auto& path : paths) {
load_image(path, pixels);
pending.push(Task{path, &pixels});
}
while (!pending.empty()) {
auto task = pending.pop();
process(task.name, *task.pixels);
}The developer explains: “After loading each image, I make a new Task and copy it into the queue. I think that saves the image, so loading the next one will not affect tasks already waiting. Task also uses const, so processing a task cannot change its image.”
Saving a Snapshot
The Snapshot class below is a separate example. An image editor uses it to save the current image before an edit, so that the user can undo the edit.
#include <memory>
struct Snapshot {
std::shared_ptr<std::vector<int>> pixels;
Snapshot clone() const {
return *this;
}
};A shared_ptr keeps the object it points to alive until its last owning handle is destroyed. Copying a shared_ptr gives another handle ownership of the same object. Assume pixels points to a vector.
Tasks that own their images
For the ownership-transfer question, the developer replaces Task and the loading loop with the following version. Each Task owns a separately created vector. The original Queue template and the final loop that retrieves tasks and calls process are unchanged for now.
struct Task {
std::string name;
std::unique_ptr<std::vector<int>> pixels;
};
Queue<Task> pending;
for (const auto& path : paths) {
Task task{path, std::make_unique<std::vector<int>>()};
load_image(path, *task.pixels);
pending.push(task);
}