Question: Please help with this code. How can i make this un faster using thread? checkNeighbor just check how many alive neighbor we have. vector GameOfLife::nextGrid(vector

Please help with this code.

How can i make this un faster using thread?

checkNeighbor just check how many alive neighbor we have.

vector > GameOfLife::nextGrid(vector > &board, thread (&myThreads)[4]){

vector > futureGrid = board;

//thread myThreads[4];

//we forced t to 4 threads and here we give each threads all the variables needed to find

//the future Grid

for(size_t i = 0; i < 4; i++){

GameOfLife x;

myThreads[i] = thread(&GameOfLife::Conway, &x, i, ref(board), ref(futureGrid));

}

//here we join all 4 threads

for(auto &t : myThreads){

t.join();

}

return futureGrid;

}

//Conway is the hearth of the algorithm where most of th works happens

void GameOfLife::Conway(int i, vector > &board, vector > &futureGrid){

int neighbor[4];

//here is where we scan the matrix and try to find the position x and y of every cell

//we split the rows to the 4 threads

for(int x = i; x < board.size(); x+=4){

for(int y = 0 ; y < board.size(); y++){

//for each cell we first find how many neighbor it has with checkNeighbor then

//we update the cell based on the rules given in futureGrid

//neighbor is an array so we avoid race condition by having multiple thread

//using the same neighbor number

neighbor[i] = checkNeighbor(board, x, y);

if((board[x][y] == 1) && (neighbor[i] >= 4)){

//alive and with more than 4 neighbor gets set to dead

futureGrid[x][y] = 0;

}else if((board[x][y] == 1) && (neighbor[i] == 0 || neighbor[i] == 1)){

//alive and with 0 or 1 neighbor gets set to dead

futureGrid[x][y] = 0;

}else if((board[x][y] == 1 || board[x][y] == 2) && (neighbor[i] == 2 || neighbor[i] == 3)){

//alive or immortal and with 2 or 3 neighbor gets copy from the current matrix

//becasue nothing changed based on Conway's rule

futureGrid[x][y] = board[x][y];

}else if((board[x][y] == 0) && (neighbor[i] == 3)){

//dead and with 3 neighbor gets set to alive

futureGrid[x][y] = 1;

}else{

//if it gets to the else means it didn't trig any of the past condition and it stay

//the same in the futureGrid too

futureGrid[x][y] = board[x][y];

}

}

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!