向Boost线程函数传递参数

Passing parameter to Boost thread function

本文关键字:参数 函数 Boost 线程      更新时间:2023-10-16

我想在一个使用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