Skip to content

Commit

Permalink
#6093: It's possible to move the std::future, but that's not advisabl…
Browse files Browse the repository at this point in the history
…e as long as some other code holds a C++ reference to it...
  • Loading branch information
codereader committed Sep 11, 2022
1 parent e885308 commit 36a765d
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 8 deletions.
18 changes: 11 additions & 7 deletions radiantcore/decl/DeclarationManager.cpp
Expand Up @@ -269,19 +269,22 @@ void DeclarationManager::waitForTypedParsersToFinish()

if (parsersToFinish.empty()) return; // nothing to do

// Add the task to the list, we need to wait for it when shutting down the module
// Move the collected parsers to the lambda
auto& task = _parserCleanupTasks.emplace_back(
// Move the collected parsers to the async lambda and clear it there
auto task = std::make_shared<std::shared_future<void>>(
std::async(std::launch::async, [parsers = std::move(parsersToFinish)]() mutable
{
// Without locking anything, just let all parsers finish their work
parsers.clear();
})
);

// Add the task to the list (but keep a strong reference to it),
// we need to wait for it when shutting down the module
_parserCleanupTasks.push_back(task);

// Release the lock and let the task run
declLock.reset();
task.get();
task->get();
}

void DeclarationManager::waitForCleanupTasksToFinish()
Expand All @@ -291,19 +294,20 @@ void DeclarationManager::waitForCleanupTasksToFinish()
// Pick the next task to wait for
auto declLock = std::make_unique<std::lock_guard<std::recursive_mutex>>(_declarationAndCreatorLock);

std::shared_future<void> task;
std::shared_ptr<std::shared_future<void>> task;

if (!_parserCleanupTasks.empty())
{
// Extract the next cleanup task
task = std::move(_parserCleanupTasks.back());
_parserCleanupTasks.pop_back();
}

if (task.valid())
if (task && task->valid())
{
// Release the lock and let it run
declLock.reset();
task.get();
task->get();
continue; // enter the next round
}

Expand Down
2 changes: 1 addition & 1 deletion radiantcore/decl/DeclarationManager.h
Expand Up @@ -70,7 +70,7 @@ class DeclarationManager :
sigc::connection _vfsInitialisedConn;

// Access allowed if the _declarationAndCreatorLock is owned
std::vector<std::shared_future<void>> _parserCleanupTasks;
std::vector<std::shared_ptr<std::shared_future<void>>> _parserCleanupTasks;

public:
void registerDeclType(const std::string& typeName, const IDeclarationCreator::Ptr& parser) override;
Expand Down

0 comments on commit 36a765d

Please sign in to comment.