2016-04-21 49 views
0

我希望我的函数在单独的线程中运行。我使用Boost库,包括像这样在我main.cppC++线程与Boost库

#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 

我试图使用线程&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" 

有人可以帮助我吗?我只想在主线程旁边运行函数。

回答

1

您应该使用bind函数来创建具有指向类成员函数的指针的函数对象,或者使您的函数成为静态函数。

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

更详细的解释: 的boost ::线程构造函数需要指向函数的指针。在正常情况下,功能语法很简单:&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绑定来创建可调用的对象。

#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; 
} 
+0

所以我必须知道的是什么? – NicMaxFen

+0

@NicMaxFen查看更新了解更多详情。从你的代码很难说你应该做什么,请发布更多的代码 – Jeka

+0

没有更多的代码与此相关。现在我得到这个错误: 致命错误LNK1104:文件“libboost_thread-vc100-mt-sgd-1_60.lib”无法打开。 我的代码行我改变了: boost :: thread(boost :: bind(&Engine :: function,&info,info)); – NicMaxFen