Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions cpp/Ice/greeter/ChatbotAMD.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#include "ChatbotAMD.h"

#include <algorithm>
#include <chrono>
#include <future>
#include <iostream>
Expand Down Expand Up @@ -33,6 +34,7 @@ ServerAMD::Chatbot::greetAsync(

// Simulate a long-running background operation by using std::async.
// Note that we're moving all arguments except current into the lambda expression.

_tasks.push_back(std::async(
std::launch::async,
[name = std::move(name), response = std::move(response), exception = std::move(exception)]()
Expand All @@ -43,6 +45,15 @@ ServerAMD::Chatbot::greetAsync(
response(os.str());
}));

// We don't want the _tasks vector to grow forever so remove all completed tasks here, without waiting.
// TODO: switch to std::erase_if when we can use C++20.
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The pre-C++20 syntax is unfortunately not very readable. See item 32 in Scott Meyers' Effective STL.

_tasks.erase(
std::remove_if(
_tasks.begin(),
_tasks.end(),
[](const auto& task) { return task.wait_for(std::chrono::seconds(0)) == std::future_status::ready; }),
_tasks.end());

// greetAsync completes immediately (releasing the Ice server thread pool thread) while the task runs in the
// background.
}
2 changes: 1 addition & 1 deletion cpp/Ice/greeter/ChatbotAMD.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace ServerAMD
class Chatbot : public VisitorCenter::Greeter
{
public:
// Waits for all tasks to complete
// Waits for all outstanding tasks to complete.
~Chatbot() override;

// Implements the pure virtual function in the base class (VisitorCenter::Greeter) generated by the Slice
Expand Down
Loading