Практическое руководство. Предоставление рабочих функций классам call и transformer
В этом разделе показано несколько способов предоставления рабочих функций классам параллелизма::call и параллелизма::преобразователя .
В первом примере показано, как передать лямбда-выражение объекту call
. Во втором примере показано, как передать объект функции в объект call
. В третьем примере показано, как привязать метод класса к объекту call
.
Для иллюстрации call
каждый пример в этом разделе использует класс. Пример использования transformer
класса см. в разделе "Практическое руководство. Использование преобразователя в конвейере данных".
Пример: класс вызова
В следующем примере показан общий способ использования call
класса. В этом примере лямбда-функция передается конструктору call
.
// call-lambda.cpp
// compile with: /EHsc
#include <agents.h>
#include <iostream>
using namespace concurrency;
using namespace std;
int wmain()
{
// Stores the result of the computation.
single_assignment<int> result;
// Pass a lambda function to a call object that computes the square
// of its input and then sends the result to the message buffer.
call<int> c([&](int n) {
send(result, n * n);
});
// Send a message to the call object and print the result.
send(c, 13);
wcout << L"13 squared is " << receive(result) << L'.' << endl;
}
В этом примере формируются следующие данные:
13 squared is 169.
Пример: класс вызова с объектом функции
Следующий пример похож на предыдущий, за исключением того, что он использует call
класс вместе с объектом-функцией (functor).
// call-functor.cpp
// compile with: /EHsc
#include <agents.h>
#include <iostream>
using namespace concurrency;
using namespace std;
// Functor class that computes the square of its input.
class square
{
public:
explicit square(ITarget<int>& target)
: _target(target)
{
}
// Function call operator for the functor class.
void operator()(int n)
{
send(_target, n * n);
}
private:
ITarget<int>& _target;
};
int wmain()
{
// Stores the result of the computation.
single_assignment<int> result;
// Pass a function object to the call constructor.
square s(result);
call<int> c(s);
// Send a message to the call object and print the result.
send(c, 13);
wcout << L"13 squared is " << receive(result) << L'.' << endl;
}
Пример. Функции для привязки объекта вызова
Следующий пример похож на предыдущий, за исключением того, что он использует функции std::bind1st и std::mem_fun для привязки call
объекта к методу класса.
Используйте этот метод, если необходимо привязать call
объект или transformer
объект к определенному методу класса вместо оператора вызова функции. operator()
// call-method.cpp
// compile with: /EHsc
#include <agents.h>
#include <functional>
#include <iostream>
using namespace concurrency;
using namespace std;
// Class that computes the square of its input.
class square
{
public:
explicit square(ITarget<int>& target)
: _target(target)
{
}
// Method that computes the square of its input.
void square_value(int n)
{
send(_target, n * n);
}
private:
ITarget<int>& _target;
};
int wmain()
{
// Stores the result of the computation.
single_assignment<int> result;
// Bind a class method to a call object.
square s(result);
call<int> c(bind1st(mem_fun(&square::square_value), &s));
// Send a message to the call object and print the result.
send(c, 13);
wcout << L"13 squared is " << receive(result) << L'.' << endl;
}
Можно также назначить результат bind1st
функции объекту std::function или использовать auto
ключевое слово, как показано в следующем примере.
// Assign to a function object.
function<void(int)> f1 = bind1st(mem_fun(&square::square_value), &s);
call<int> c1(f1);
// Alternatively, use the auto keyword to have the compiler deduce the type.
auto f2 = bind1st(mem_fun(&square::square_value), &s);
call<int> c2(f2);
Компиляция кода
Скопируйте пример кода и вставьте его в проект Visual Studio или вставьте его в файл с именем call.cpp
, а затем выполните следующую команду в окне командной строки Visual Studio.
cl.exe /EHsc call.cpp
См. также
Библиотека асинхронных агентов
Асинхронные блоки сообщений
Практическое руководство. Использование преобразователя в конвейере данных
Класс call
Класс transformer