2016-02-26 71 views
0

我在C++ 11中尝试了一下多线程,并且我得到了一些奇怪的结果。我有以下的代码,它运行得很好(tree_node是一个自定义类)试用多线程

#include <thread> 
#include <mutex> 
#include "cards.h" 
mutex m; 

//a function that prints the node and his children 
void nodes_print(tree_node& a, std::streampos pos_nodo){ 

    cout << a.player.suit << a.player.value << " "; 
    cout << a.versus.suit << a.versus.value << " "; 

    if(a.nodes>0){ 
     for (int i=0; i<a.nodes; i++){ 
      //children_nodes stores node's children 
      nodes_print(a.children_nodes[i], o.tellp()); 
     } 
    } 
    else return; 
}  

void node_child(tree_node a){ 
    m.lock(); 
    cout << "thread " << this_thread::get_id(); 
    a.children();  //a function member of class tree_node 
    nodes_print(a,0); 
    m.unlock(); 
} 

int main(){ 
    tree_node node_1; 
    thread t(node_child, node_1); 
    if(t.joinable()) t.join(); 
    return 0; 
} 

我的问题是我需要的功能node_child得到一个参考tree_node。但是当我尝试如下

tree_node node_1; 
thread t(node_child, node_1); 
if(t.joinable()) t.join(); 

使用的功能void node_child(tree_node& a)调用线程我收到以下错误/usr/include/c++/4.9/functional:1665:61: error: no type named ‘type’ in ‘class std::result_of<void (*(tree_node))(tree_node&)>’

搜索互联网上我发现了一个帖子里这个问题是使用std::ref(node_1)包装解决,但我我想知道发生错误时会发生什么。在发布之前,我发现问题与更多的线程访问相同的资源相关,但不能将这种情况与我的相关,因为我只有一个线程。

编辑:加入tree_node定义在头cards.h包括

class tree_node{ 
    tree_node();//ctor 
    tree_node(const tree_node&);//copy ctor 
    tree_node(tree_node&&); //move ctor 
    tree_node& operator= (tree_node);//assignment with copy-swap idiom 

    cards * player; 
    cards * versus; 
    int * suits_player; 
    int * suits_versus; 
    tree_node * children_nodes; 

    void children(); 

} 

我会尽快,我可以检查的答案,只是很快就过去了,检查

+0

向我们展示了一个'tree_node'类的定义。 – SergeyA

+0

也许你应该包括'tree_node'的标头 – Thomas

+0

从[this](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57716)gcc bug报告页面看来,它看起来像是真正的错误尝试将右值绑定到左值引用。我不知道为什么错误信息会非常无用。 –

回答

2

的问题是,函数通过左值引用获取参数。在内部,std::thread使用std::decay,该参数将参数从参数类型中删除。当这些类型被转发给函数时,结果是传递一个右值给引用,失败。

你没有得到一个“不能绑定到右值左值参考”错误的原因是因为模板实例化过程中,std::result_of使用是推断通过调用函数表达式中使用decltype返回类型。但是,该呼叫无效,所以type未在result_of内定义。

cppreference

type ...仅定义如果F可与参数ArgTypes称为...在未计算的上下文中(因为C++ 14)。

F(你的函数)不能被调用,所以type是从来没有定义,所以编译器给你一个错误失踪type定义。

+0

这是一团糟,感谢您的解释。所以唯一的方法是使用'std :: ref'? – luigi