2016-04-21 108 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