fix an issue that nf7::Context could be deleted before its tasks end

This commit is contained in:
falsycat 2022-06-09 17:57:11 +09:00
parent c178c27966
commit 1a795fc387

25
main.cc
View File

@ -76,14 +76,14 @@ class Env final : public nf7::Env {
::Env::Pop(); ::Env::Pop();
} }
void ExecMain(const std::shared_ptr<Context>&, Task&& task) noexcept override { void ExecMain(const std::shared_ptr<Context>& ctx, Task&& task) noexcept override {
main_.Push(std::move(task)); main_.Push({ctx, std::move(task)});
} }
void ExecSub(const std::shared_ptr<Context>&, Task&& task) noexcept override { void ExecSub(const std::shared_ptr<Context>& ctx, Task&& task) noexcept override {
sub_.Push(std::move(task)); sub_.Push({ctx, std::move(task)});
} }
void ExecAsync(const std::shared_ptr<Context>&, Task&& task) noexcept override { void ExecAsync(const std::shared_ptr<Context>& ctx, Task&& task) noexcept override {
async_.Push(std::move(task)); async_.Push({ctx, std::move(task)});
} }
void Handle(const File::Event& e) noexcept override void Handle(const File::Event& e) noexcept override
@ -177,9 +177,10 @@ class Env final : public nf7::Env {
std::unordered_map<File::Id, std::vector<Watcher*>> watchers_map_; std::unordered_map<File::Id, std::vector<Watcher*>> watchers_map_;
std::unordered_map<Watcher*, std::vector<File::Id>> watchers_rmap_; std::unordered_map<Watcher*, std::vector<File::Id>> watchers_rmap_;
Queue<Task> main_; using TaskItem = std::pair<std::shared_ptr<nf7::Context>, Task>;
Queue<Task> sub_; Queue<TaskItem> main_;
WaitQueue<Task> async_; Queue<TaskItem> sub_;
WaitQueue<TaskItem> async_;
std::mutex mtx_; std::mutex mtx_;
std::condition_variable cv_; std::condition_variable cv_;
@ -241,7 +242,7 @@ class Env final : public nf7::Env {
// exec main tasks // exec main tasks
while (auto task = main_.Pop()) while (auto task = main_.Pop())
try { try {
(*task)(); task->second();
} catch (Exception&) { } catch (Exception&) {
Panic(); Panic();
} }
@ -252,7 +253,7 @@ class Env final : public nf7::Env {
const auto task = sub_.Pop(); const auto task = sub_.Pop();
if (!task) break; if (!task) break;
try { try {
(*task)(); task->second();
} catch (Exception&) { } catch (Exception&) {
Panic(); Panic();
} }
@ -266,7 +267,7 @@ class Env final : public nf7::Env {
while (alive_) { while (alive_) {
while (auto task = async_.Pop()) while (auto task = async_.Pop())
try { try {
(*task)(); task->second();
} catch (Exception&) { } catch (Exception&) {
// TODO: how to handle? // TODO: how to handle?
} }