我试图做一个迷宫解决算法,我已经决定使用BFS来尝试找到最短的路径(因为我无法确定我离出口的距离,我和#39;我不确定如何使用A *)。
为了加快速度,我决定采用多线程方法,并且有4个同步线程探索当前单元格的所有四个可能的行进方向(只有一个线程在执行实际运动)
我目前的解决方案如下:
static void Main()
{
while (true)
{
fullCount.WaitOne(); //fullCount is initialized to 4
queueLock.WaitOne(); // binary semaphore for queue access
if (cellQueue.Count > 0)
{
parent = cellQueue.Dequeue();
}
queueLock.Release();
if (parent.isAtEnd())
{
Console.WriteLine("We made it!");
return;
}
Console.WriteLine("Currently at X: {0}, Y:{1}", parent.x, parent.y);
Thread travelNorth = new Thread(() => explore("NORTH", parent.north));
Thread travelSouth = new Thread(() => explore("SOUTH", parent.south));
Thread travelEast = new Thread(() => explore("EAST", parent.east));
Thread travelWest = new Thread(() => explore("WEST", parent.west));
travelNorth.Start();
travelSouth.Start();
travelEast.Start();
travelWest.Start();
}
}
}
// function that each thread calls
static void explore(string direction, string status)
{
if (status == "UNEXPLORED)
{
bool movableDirection = lookAhead(direction);
if (movableDirection)
{
Cell tempCell = grabCell(direction); //gets the cell that lies in specified direction
queueLock.WaitOne();
cellQueue.Enqueue(tempCell);
queueLock.Release();
fullCount.Release(); //allow main thread to continue if queue is empty.
}
}
我遇到的问题是我的Main()
方法在fullCount.WaitOne();
行停止,表明队列为空,我们正在等待队列不为空。而且非常烦人(就像所有多线程问题一样),我不知道在哪里/为什么我会得到我的队列为空的情况,除非我以某种方式在迷宫中进入循环。