Skip to content

Instantly share code, notes, and snippets.

@renestein
Created September 2, 2020 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save renestein/1cd509bf7370f9e5b288e1e5aa64f2ee to your computer and use it in GitHub Desktop.
Save renestein/1cd509bf7370f9e5b288e1e5aa64f2ee to your computer and use it in GitHub Desktop.
//Actor inherits from the ActorPolicy class.
class TestActor : public Actors::ActorPolicy
{
public:
TestActor() : ActorPolicy{}
{
}
//Fire & forget method runs in the actor message loop.
void RunVoidMethod(std::function<void()> scheduleFunction)
{
//Use the inherited ScheduleFunction method from the ActorPolicy to add the message to the actor queue.
ScheduleFunction([scheduleFunction]
{
scheduleFunction();
return Tasks::GetCompletedTask();
});
}
//Method returns result of the processing wrapped in the Task<int>.
Tasks::Task<int> ProcessInt(int number)
{
//Use the inherited ScheduleFunction method from the ActorPolicy to add the message to the actor queue.
//ScheduleFunction returns Task<T>.
return ScheduleFunction([number] {
//Simply return the argument.
return number;
});
}
//Method returns result of the processing wrapped in the Task<int>.
Tasks::Task<int> ProcessInt(std::function<int(int)> processIntFunc, int number)
{
//Use the inherited ScheduleFunction method from the ActorPolicy to add the message to the actor queue.
//ScheduleFunction returns Task<T>.
return ScheduleFunction([number, processIntFunc] {
//Run the function in the actor 'logical' thread.
return processIntFunc(number);
});
}
[...]
};
//Check that the message in the actor qeueue is processed.
TEST(ActorPolicy, ScheduleFunctionWhenMethodCalledThenTaskIsCompletedWithExpectedResult)
{
const int EXPECTED_RESULT = 10;
TestActor actor;
//Add message to the actor queue.
auto intTask = actor.ProcessInt(EXPECTED_RESULT);
//Wait for the actor task.
intTask.Wait();
//Check that the actor method returns expected value.
ASSERT_EQ(EXPECTED_RESULT, intTask.Result());
}
//Sum the data in the actor.
TEST(ActorPolicy, ScheduleFunctionWhenCalledThenAllFunctionsAreProcessedSequentially)
{
const int SUM_TO = 100;
const int EXPECTED_RESULT = SUM_TO * (SUM_TO + 1) / 2;
TestActor actor;
auto intTask = Tasks::Task<int>::InvalidPlaceholderTaskCreator()();
auto sumResult = 0;
for (int i = 0; i <= SUM_TO; ++i)
{
//Call the actor method ProcessInt (std::function<int(int)> processIntFunc, int number) overload.
intTask = actor.ProcessInt([&sumResult](int number)
{
sumResult += number;
return sumResult;
}, i);
}
//Wait for the last processing result.
intTask.Wait();
auto lastTaskResult = intTask.Result();
ASSERT_EQ(EXPECTED_RESULT, lastTaskResult);
ASSERT_EQ(EXPECTED_RESULT, sumResult);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment