vendredi 26 février 2016

Experimenting with multithreading

I'm experimenting a bit with multi-threading in C++11, and I'm getting some strange results. I have the following code and it runs just fine (tree_node is a custom class)

#include <thread>
#include <mutex>
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;
}

My problem is that I need the function node_child to get a reference to tree_node. But when i try to use the function void node_child(tree_node& a) calling the thread as following

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

I get the following error /usr/include/c++/4.9/functional:1665:61: error: no type named ‘type’ in ‘class std::result_of<void (*(tree_node))(tree_node&)>’

Searching on internet I found a post where this problem was resolved using std::ref(node_1) wrapper, but I'm wondering what happens when getting that error. In the post I found before the problem was related to more thread accessing the same resource, but can't relate that case to mine since I have only a single thread.

Aucun commentaire:

Enregistrer un commentaire