向Boost线程函数传递参数
Passing parameter to Boost thread function
我想在一个使用boost库的新线程中调用这个参数化函数。
/**
* 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;
}
我可以使用以下代码调用
调用非参数化函数boost:: asio::::线程workerThread (workerFunc);
当我尝试为参数化函数使用以下代码时:
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;
}
我得到以下错误,
/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
^
当您在名称空间detail
中使用一个类时,就会提示出问题了。这个命名空间应该被认为是私有的,而不是boost接口的一部分。
用boost::thread
代替:
#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;
}
输出:main: startup
main: waiting for thread
Worker: running - Hello world
Worker: finished - Hello world
main: done
相关文章:
- 将可变参数函数的参数封装在类实例中
- QML 使用带有参数C++函数
- 使用可变参数函数作为模板参数
- 如何在C++中伪造虚拟可变参数函数模板?
- 为什么可变参数函数不适用于模板
- C++ std::functional 中的可变参数函数模板
- 可变参数函数指针的定义对于VxWorks spyLib来说不清楚
- 使用可变参数函数覆盖具有不同函数签名的虚函数
- 考虑引用和常量的可变参数函数包装器
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 在可变参数函数中转发特定范围的参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 使用带有一个参数函数的递归找到数字的平方
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 多个可变参数函数的单个模板参数包?
- 参数数据类型未知的可变参数函数
- 可变参数函数参数包扩展
- 使用模板可变参数函数将多个参数传递给另一个函数
- 对可变参数函数的递归调用的链接器错误
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类