samedi 28 février 2015

Converting single threaded program to multithreaded


I am doing a HW assignment (so please don't provide solution code) and I'm stuck on how to convert single threaded code to multithreaded code. I have written some code to solve my problem however I'm not sure how I can convert the code to a multithreaded program without access to the SlidingPuzzleState s member functions. I would appreciate a nudge in the right direction as I'm at loss as to how to split the work up among the threads ands do the work without access to the functions in the SlidingPuzzleState. I have the following code:



/** Worker Thread:
* Work queue: will send a starting location from which we do workSize work
* dataLock: a lock used when writing to the BFS data
* data: the depths for the BFS data
* seenStates: a counter to mark how many states have had their depths updated
* depth: the current depth in the BFS
*/
void WorkerThread(SharedLList<uint32_t> *workQueue, std::mutex *dataLock, uint8_t *data, uint32_t *seenStates, int depth)
{
//I need to implement this so I can send the work to the threads
}
void DoBFS(int numThreads)
{
std::cout << "Running with " << numThreads << " threads\n";
// By default, starts at goal state
SlidingPuzzleState s;
LList<int> moves;
SharedLList<uint32_t> workQueue;
std::mutex lock;
std::thread **threads = new std::thread*[numThreads];

uint8_t *stateDepths = new uint8_t[s.GetMaxRank()];

// set all values to 255
memset(stateDepths, 255, s.GetMaxRank());
uint32_t seenStates = 1;
stateDepths[s.Rank()] = 0;
int currDepth = 0;


std::cout.setf( std::ios::fixed, std:: ios::floatfield ); // floatfield set to fixed
std::cout.precision(2);

while (seenStates != s.GetMaxRank())
{


for (int x = 0; x < s.GetMaxRank(); x++)
{
if (stateDepths[x] == currDepth)
{
s.Unrank(x);
s.GetMoves(moves);
while (moves.IsEmpty() == false)
{
s.ApplyMove(moves.PeekFront());
uint32_t rank = s.Rank();
s.UndoMove(moves.PeekFront());
moves.RemoveFront();

if (stateDepths[rank] == 255)
{
stateDepths[rank] = currDepth+1;
seenStates++;
}
}
}
}
}


The code I have tried is (in the BFS while loop):



for (int i = 0; i < numThreads; i++)
{
threads[i] = new std::thread(WorkerThread, &workQueue, &lock, &stateDepths, currDepth);
}

for(int i = 0; i < s.GetMaxRank(); i++)
{
if (stateDepths[i] == currDepth)
{
workQueue.AddBack(i); //Without access to the ranking functions in my thread function I'm not sure how this is even useful to me.
}
}

for (int x = 0; x < numThreads; x++)
{
threads[x]->join();
delete threads[x];
}



Aucun commentaire:

Enregistrer un commentaire