C# BFS的生产者-消费者模型
我正在尝试做一个迷宫求解算法,我决定使用BFS来尝试寻找最短路径,因为我无法确定我离出口有多近,我不确定如何使用a* 为了加快速度,我决定采用多线程的方法,让4个线程同时探索当前单元格中所有四个可能的移动方向,只有一个线程进行实际的移动 我当前的解决方案如下所示:C# BFS的生产者-消费者模型,c#,multithreading,algorithm,producer-consumer,C#,Multithreading,Algorithm,Producer Consumer,我正在尝试做一个迷宫求解算法,我决定使用BFS来尝试寻找最短路径,因为我无法确定我离出口有多近,我不确定如何使用a* 为了加快速度,我决定采用多线程的方法,让4个线程同时探索当前单元格中所有四个可能的移动方向,只有一个线程进行实际的移动 我当前的解决方案如下所示: static void Main() { while (true) { fullCount.WaitOne(); //fullCount is initialized to 4 queu
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.
}
}
我遇到的一个问题是,我的主要方法停止在fullCount.WaitOne;行,表示队列为空,我们正在等待队列不为空。和所有复杂的问题一样,令人烦恼的是,我不知道在哪里/为什么我的队列是空的,除非我在迷宫中不知何故进入了一个循环。在某个方向上探索是否意味着严格地朝那个方向走,永远不要转向?探索意味着严格地朝那个方向走,仅适用于周围的单元,即如果向北,则仅向北一个单元等。我对这种使用线程的方式有一些疑问。您需要了解新线程的成本以及避免死锁等所需的所有操作。在主循环的末尾添加一个thread.Sleep500和一个非常小的迷宫。这会使您的问题很早出现吗?此外,请在问题中添加变量声明。