I'm trying to understand thread pools using boost.
I've written the following code:
#include <boost/asio/post.hpp>
#include <boost/asio/thread_pool.hpp>
#include <boost/bind/bind.hpp>
#include <iostream>
#include <chrono>
#include <thread>
class A {
public:
void asyncFunc(int i)
{
std::this_thread::sleep_for(std::chrono::seconds(3));
std::cout<< i ;
}
void beforeFunc()
{
std::cout<< "Before\n";
}
void afterFunc()
{
std::cout<< "After\n";
}
void otherFunc()
{
boost::asio::thread_pool pool(4);
for(int i = 0; i < 1000; i )
{
beforeFunc();
boost::asio::post(pool, boost::bind(&A::asyncFunc, 3));
boost::asio::post(pool, boost::bind(&A::asyncFunc, 0));
boost::asio::post(pool, boost::bind(&A::asyncFunc, 2));
boost::asio::post(pool, boost::bind(&A::asyncFunc, 1));
afterFunc();
}
pool.join();
}
};
int main()
{
A a;
a.otherFunc();
}
But I get errors related to boost::get_pointer. (https://wandbox.org/#)
The idea would be to execute 4 asyncFuncs in parallel, but always after beforeFunc() and before afterFunc() as they will be dependent.
Do you know what I'm doing wrong in this code, or how could I achieve better what I'm trying?
CodePudding user response:
You are binding non-static member functions. The first argument for non-static member function is the implicit this
argument. You are passing integers there. Add the missing this
:
post(pool, boost::bind(&A::asyncFunc, this, 3));
post(pool, boost::bind(&A::asyncFunc, this, 0));
post(pool, boost::bind(&A::asyncFunc, this, 2));
post(pool, boost::bind(&A::asyncFunc, this, 1));
#include <boost/asio.hpp>
#include <boost/bind/bind.hpp>
#include <chrono>
#include <iostream>
#include <thread>
class A {
public:
void asyncFunc(int i) {
std::this_thread::sleep_for(std::chrono::seconds(3));
std::cout << i;
}
void beforeFunc() { std::cout << "Before\n"; }
void afterFunc() { std::cout << "After\n"; }
void otherFunc() {
boost::asio::thread_pool pool(4);
for (int i = 0; i < 10/*00*/; i ) {
beforeFunc();
post(pool, boost::bind(&A::asyncFunc, this, 3));
post(pool, boost::bind(&A::asyncFunc, this, 0));
post(pool, boost::bind(&A::asyncFunc, this, 2));
post(pool, boost::bind(&A::asyncFunc, this, 1));
afterFunc();
}
pool.join();
}
};
int main() {
std::cout << std::unitbuf;
A a;
a.otherFunc();
}
Prints e.g.
Before
After
Before
After
Before
After
Before
After
Before
After
Before
After
Before
After
Before
After
Before
After
Before
After
1032321030213012302130123012032131023102
Achieving What You're Trying
You won't really be done because you don't synchronize before the afterFunc()
. You can do that in various ways: