【问题标题】:C++ Threading with Boost Library带有 Boost 库的 C++ 线程
【发布时间】:2016-04-21 08:00:40
【问题描述】:

我希望我的函数在单独的线程中运行。我使用 Boost 库并在我的main.cpp 中包含这样的内容:

#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

我希望线程像这样开始:

boost::thread ethread(Engine::function,info);
// info is an object from the class Engine and i need this in the
// function

我的Engine 类在func.h 中,函数如下所示:

void Engine::function(Engine info)
{
    //STUFF
    boost::this_thread::sleep(boost::posix_time::milliseconds(1));
}

顺便说一句:线程的sleep 函数对吗?

每次我想编译它都会给我这个错误:

error C3867: "Engine::function": function call missing argument list; use '&Engine::function' to create a pointer to member

我尝试在线程中使用&amp;Engine::function,出现这个错误:

error C2064: term does not evaluate to a function taking 2 arguments

我也试过了:

boost::thread ethread(Engine::function,info, _1);

然后出现了这个错误:

error C2784: "result_traits<R,F>::type boost::_bi::list0::operator [](const boost::_bi::bind_t<R,F,L> &) const"

有人可以帮我解决这个问题吗?我只想在主线程旁边运行函数。

【问题讨论】:

    标签: c++ multithreading boost


    【解决方案1】:

    您应该使用绑定函数来创建具有指向类成员函数的指针的功能对象或使您的函数静态。

    http://ru.cppreference.com/w/cpp/utility/functional/bind

    更详细的解释: boost::thread 构造函数需要指向函数的指针。如果是普通函数,语法很简单:&amp;hello

    #include <boost/thread/thread.hpp>
    #include <iostream>
    void hello()
    {
        std::cout << "Hello world, I'm a thread!" << std::endl;
    }
    
    int main(int argc, char* argv[])
    {
        boost::thread thrd(&hello);
        thrd.join();
        return 0;
    }
    

    但是,如果您需要指向类函数的指针,您必须记住此类函数具有隐式参数 - this 指针,因此您也必须传递它。您可以通过使用 std::bind 或 boost bind 创建可调用对象来做到这一点。

    #include <iostream>
    #include <boost/thread.hpp>
    
    class Foo{
    public:
        void print( int a )
        {
            std::cout << a << std::endl;
        }
    };
    
    int main(int argc, char *argv[])
    {
        Foo foo;
        boost::thread t( std::bind( &Foo::print, &foo, 5 ) );
        t.join();
    
    
        return 0;
    }
    

    【讨论】:

    • 那我要知道什么?
    • @NicMaxFen 查看更新了解更多详情。从你的代码很难说你到底应该做什么,请发布更多代码
    • 没有更多与此相关的代码。现在我收到此错误:致命错误 LNK1104:无法打开文件“libboost_thread-vc100-mt-sgd-1_60.lib”。我更改了我的代码行: boost::thread(boost::bind(&Engine::function,&info, info));
    • @NicMaxFen 您正在调用 info 对象的方法并将其作为参数传递!你肯定做的很奇怪。这是一个典型的链接器错误“链接器找不到boost库。一些boost组件不仅仅是头文件,它们使用自动链接隐式链接库
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-03
    • 2011-02-09
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    相关资源
    最近更新 更多