Reputation: 113
I want to call this parametrized function in a new thread using boost library.
/**
* Temporary function to test boost threads
*/
void workerFunc(const char* msg, unsigned delaySecs)
{
boost::posix_time::seconds workTime(delaySecs);
std::cout << "Worker: running - " << msg << std::endl;
// Pretend to do something useful...
boost::this_thread::sleep(workTime);
std::cout << "Worker: finished - " << msg << std::endl;
}
I was able to call non-parametrized function using following code call
boost::asio::detail::thread workerThread(workerFunc);
When I try to use following code for parametrized function:
int main()
{
std::cout << "main: startup" << std::endl;
const char* name = "Hello world";
boost::asio::detail::thread workerThread(workerFunc, name, 5);
std::cout << "main: waiting for thread" << std::endl;
workerThread.join();
std::cout << "main: done" << std::endl;
}
I get following error,
/home/hassan/ClionProjects/sme/Driver.cpp:106:41: error: no matching constructor for initialization of 'boost::asio::detail::thread' (aka 'boost::asio::detail::posix_thread')
boost::asio::detail::thread workerThread(workerFunc, name, 5);
^ ~~~~~~~~~~~~~~~~~~~
/usr/include/boost/asio/detail/posix_thread.hpp:42:3: note: candidate constructor template not viable: requires at most 2 arguments, but 3 were provided
posix_thread(Function f, unsigned int = 0)
^
/usr/include/boost/asio/detail/posix_thread.hpp:36:7: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 3 were provided
class posix_thread
^
Upvotes: 2
Views: 3419
Reputation: 69854
The clue that something is up is when you use a class in namespace detail
. This namespace should be considered to be private, and not part of boost's interface.
Use boost::thread
instead:
#include <iostream>
#include <boost/thread.hpp>
#include <boost/functional.hpp>
void workerFunc(const char* msg, unsigned delaySecs)
{
boost::posix_time::seconds workTime(delaySecs);
std::cout << "Worker: running - " << msg << std::endl;
// Pretend to do something useful...
boost::this_thread::sleep(workTime);
std::cout << "Worker: finished - " << msg << std::endl;
}
int main()
{
std::cout << "main: startup" << std::endl;
const char* name = "Hello world";
boost::thread workerThread(workerFunc, name, 5);
std::cout << "main: waiting for thread" << std::endl;
workerThread.join();
std::cout << "main: done" << std::endl;
// edit: fixed in response to comment
return 0;
}
output:
main: startup
main: waiting for thread
Worker: running - Hello world
Worker: finished - Hello world
main: done
Upvotes: 3