0

Im trying to do multi-threading and below is the function that I want to be the thread:

void  AIShell::vertCombos ( int &my_combo, int& opp_combo, int &score, int ** gameState){
   int my_combos = 0;
   int opp_combo =0;
   it score = 0;
  for (int i = 0; i < numCols; i++){
    my_combo = 0;
    opp_combo = 0;
    for (int j = 0; j < numRows; j++){
      if (gameState[i][j] == NO_PIECE){
        ++my_combo;
        ++opp_combo;
      }
      else if (gameState[i][j] == AI_PIECE){
        ++my_combo;
        opp_combo = 0;
      }
      else if (gameState[i][j] == HUMAN_PIECE){
        my_combo = 0;
        ++opp_combo;
      }

      if (my_combo == k){
        ++score;
        my_combo = k-1;
      }
      if (opp_combo == k){
        --score;
        opp_combo = k-1;
      }
    }
  }
  pthread_exit(NULL);
}

Im trying to create the thread in another function by doing:

 pthread_create (0, NULL, vertCombos,my_combo, opp_combo, score, gameState);

But i get the error:

AIShell.cpp: In member function ‘int AIShell::heuristic(int**)’: AIShell.cpp:224:82: error: cannot convert ‘AIShell::vertCombos’ from type ‘void (AIShell::)(int&, int&, int&, int**)’ to type ‘void* ()(void)’ pthread_create (0, NULL, vertCombos,my_combo, opp_combo, score, gameState); ^

Ive also tried doing the following with the same above function:

std::thread t1(vertCombos,my_combo, opp_combo, score, gameState);

then

t1.join();

but that throws errors as well. Ive also tried:

 std::thread t1(vertCombos,my_combo, opp_combo, score, std::ref(gameState));

and

 std::thread t1(AIShell::vertCombos,my_combo, opp_combo, score, gameState);

Im not understanding how to fix the problem, thanks!

Suha s
  • 9
  • 2
  • Possible duplicate of [Start thread with member function](http://stackoverflow.com/questions/10673585/start-thread-with-member-function) – user4581301 Oct 29 '16 at 19:19

1 Answers1

0

In case vertCombos is not a static method, you should pass instance of an object AIShell as a second parameter into thread constructor:

std::thread t(&AIShell::vertCombos, aiShellObj, std::ref(my_combo), std::ref(opp_combo), std::ref(score), gameState);

You could use lambda function instead of function pointer:

// These parameters will be captured by lambda
int my_combo, opp_combo, score;
int **gameState = nullptr;

// gameState initialization is skipped

std::thread t([&](AIShell* obj){ obj->vertCombos(my_combo, opp_combo, score, gameState); }, &shell);

Otherwise, if vertCombos is static method:

std::thread t(&AIShell::vertCombos, std::ref(my_combo), std::ref(opp_combo), std::ref(score), gameState);
Nikita
  • 6,270
  • 2
  • 24
  • 37