我在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();
}
我会尽快,我可以检查的答案,只是很快就过去了,检查
向我们展示了一个'tree_node'类的定义。 – SergeyA
也许你应该包括'tree_node'的标头 – Thomas
从[this](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57716)gcc bug报告页面看来,它看起来像是真正的错误尝试将右值绑定到左值引用。我不知道为什么错误信息会非常无用。 –