2015-04-12 93 views
1

给定对象x,我想启动一个新线程来调用x.a()甚至x.a(1,2,3)。我可以使用boost::thread为非成员函数执行此操作;但我如何为会员功能做到这一点?我如何通过this指针?一般来说,有很多STL和Boost代码和模板将代码作为参数,但是,由于这不是真正在C++中定义的(函数不是一级vals,本地lambda支持)我很困惑他们是如何定义的。我可以做试验和错误,但我想要更清洁的人,更可靠。C++ Boost.Thread:传递对象的方法

更新:我的问题主要涉及传递一个方法;当我尝试做什么将是明显的语法(ClassName::method_name, instance)我得到invalid use of non-static member functionerror: no matching function to call。如果你能够在非静态方法中显示使用Boost.thread的正确语法,这将有所帮助。

UPDATE 2:我发现我为什么要为此而苦苦挣扎。给出的答案,比如@OrDinari,适用于boost::thread。但是,当我尝试使用thread_group,就是thread_group::create_thread,我得到这个错误:

error: no matching function for call to ‘boost::thread_group::create_thread(void (C::*)(), C*)’ 

所以:

  1. 为什么它的根单丝工作,但不是线程组?
  2. 如何在组中创建线程来运行成员函数?
+2

C++确实具有原生lambda支持。 – Puppy

+0

如果你是一个原始的野蛮人,你也可以使用boost :: bind。 – Puppy

+0

这已经在StackOverflow –

回答

2

下面是一个例子:

 boost::thread _commandControl(&Client::commandControl, &client); 

此创建一个新的线程,使用客户端对象方法commandControl,从指定的客户端Client实例。

这里有点一块较大的代码,可能会更容易理解:

Client client(host, port); 
std::cout << "Pick interface (1) Terminal (2) Menu:\n"; 
char interfaceMode; 
std::cin >> interfaceMode; 
while (!client.setMode(interfaceMode)) { 
    std::cout << "\nInvalid choice! try again (1) For Terminal (2)For Menu:"; 
    std::cin >> interfaceMode; 
} 
try { 
    std::cin.ignore(); 
    if (client.connect()) { 
     try { 

      boost::thread _commandControl(&Client::commandControl, &client); 
      boost::thread _checkQueue(&Client::checkQueue, &client); 
      _checkQueue.join(); 
      if (client.checkAlive() == false)throw ConnectionDCexception(); 
      _commandControl.join(); 
      client.close(); 
     } 
     catch (std::exception &e) { 
      std::cout << "\n" << e.what(); 
     } 
    } 
    else { 
     std::cout << "\nFailed to initiate connecting, exiting..."; 
    } 
} 

你正在寻找的主要事情是:

Client client(host, port); 

boost::thread _commandControl(&Client::commandControl, &client); 
boost::thread _checkQueue(&Client::checkQueue, &client); 

各自是不同的线程,从类Client的同一个实例(客户端)。

+0

谢谢 - 请参阅更新,这对thread_group失败。你可以看一下吗? – SRobertJames

0

如果使用C++ 11,你可以使用lambda表达式:

#include <iostream> 
#include <thread> 

class Foo 
{ 
public: 
    void foo() 
    { 
     std::cout << "Foo thread: " << std::this_thread::get_id() << std::endl; 
    } 
}; 

int main() { 
    std::cout << "Main thred: " << std::this_thread::get_id() << std::endl; 

    Foo foo; 
    std::thread t1([&foo]() {foo.foo();}); 
    t1.join(); 

    return 0; 
} 

您可以替换的std ::线程的boost ::线程。