将参数传递给Boost线程函数

时间:2015-08-21 21:24:26

标签: c++ multithreading boost

我想使用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 :: detail :: thread 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
      ^

1 个答案:

答案 0 :(得分:3)

当你在命名空间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