Я пытаюсь создать вдохновляемый контекст Golang в C ++ для использования в рабочих потоках и других задачах. Я старался не использовать необработанные указатели, но с тех пор, как я начал писать код C ++, я всегда чувствую, что не уверен, как ведет себя мой код. Я хочу отзывы о моей реализации и потенциальных ошибках. Многие константы были предложением от Linter: < /p>
#pragma once
#include
#include
#include
#include
#include
class Context : public std::enable_shared_from_this {
public:
Context() : cancelled(false) {
}
~Context() {
cancel();
detachFromParent();
}
static std::shared_ptr fromParent(std::shared_ptr &parent) {
auto context = std::make_shared();
if (parent) {
parent->appendChild(context);
context->parent = parent; // Use weak_ptr to prevent circular reference
}
return context;
}
void cancel() {
std::lock_guard lock(mtx);
cancelled = true;
for (const auto &child: children) {
try {
child->cancel();
} catch (...) {
continue;
}
}
cv.notify_all(); // Wake up all waiting threads
}
bool isCancelled() const {
return cancelled.load();
}
void waitForCancel() {
std::unique_lock lock(mtx);
cv.wait(lock, [&]() { return cancelled.load(); });
}
void appendChild(const std::shared_ptr &child) {
std::lock_guard lock(mtx);
children.push_back(child);
}
void removeChild(const std::shared_ptr &child) {
std::lock_guard lock(mtx);
children.remove(child);
}
void detachFromParent() {
if (auto parent_ptr = parent.lock()) {
parent_ptr->removeChild(shared_from_this());
}
}
private:
std::atomic cancelled;
std::mutex mtx;
std::condition_variable cv;
std::list children;
std::weak_ptr parent; // Weak pointer to break circular reference
};
Подробнее здесь: https://stackoverflow.com/questions/795 ... management