2017-04-14 46 views
1

我不知道這個問題是統一專用的,所以也許其他C#開發人員可以幫我太:)多線程如果我開始超過1其他線程

所以我實際上是試圖實現不起作用我自己的A *算法和版本,以提高性能我想實際路徑尋找每一個求職者是多線程:

One active seeker

它工作得很好,直到我激活第二導引頭的那一刻: Two active seekers

就像你可以看到它在15次迭代後停止(根據我調用多少個文​​本輸出 - >我猜測線程在一段時間後被殺死),並且第一次啓動的線程會被以下。

我使用C#ThreadPool類爲我的線程管理,但我也嘗試使用Thread類。這是相同的結果。

實現我的穿線:

public static void RequestPath(PathRequest _request) 
{ 
    Debug.Log("Queueing PathRequest..."); 
    ThreadPool.QueueUserWorkItem(instance.StartThreadedPathfinding, _request); 
} 

調用的方法:

private void StartThreadedPathfinding(object _stateInfo) 
{ 
    PathRequest request = (PathRequest)_stateInfo; 
    m_pathfinder.FindPath(request, OnPathFound); 
} 

而且FindPath

public void FindPath(PathRequest _request, Action<PathResult> _callback) 
{ 
    Debug.Log("Starting A* Algorithm"); 
    BinaryHeap<Node> openList = new BinaryHeap<Node>(GridSize); 
    HashSet<Node> closedList = new HashSet<Node>(); 

    Node startNode = _request.Start; 
    Node targetNode = _request.Target; 

    bool success = false; 

    openList.Add(startNode); 

    while (openList.Count > 0) 
    { 
     Debug.Log(Thread.CurrentThread.ManagedThreadId + ": " + Thread.CurrentThread.ThreadState.ToString()); 
     Node currentNode = openList.RemoveFirst(); 

     if (currentNode == targetNode) 
     { 
      // TODO: Path found -> _callback 
      success = true; 
      Debug.Log("Path found"); 
      _callback(new PathResult(null, success, _request.Callback)); 
      return; 
     } 

     closedList.Add(currentNode); 

     foreach (Node neighbour in currentNode.m_neighbours) 
     { 
      if (closedList.Contains(neighbour)) 
      { 
       continue; 
      } 

      int tentativeG = currentNode.m_gCost + GetDistance(currentNode, neighbour); 
      if (openList.Contains(neighbour) && tentativeG > neighbour.m_gCost) 
      { 
       continue; 
      } 

      neighbour.m_parent = currentNode; 
      neighbour.m_gCost = tentativeG; 
      neighbour.m_hCost = GetDistance(neighbour, targetNode); 

      if (openList.Contains(neighbour)) 
      { 
       openList.UpdateItem(neighbour); 
      } 
      else 
      { 
       openList.Add(neighbour); 
      } 
     } 
    } 

    // TODO: No path to the target exists -> calculate some path 
    success = false; 
    Debug.Log("No existing path"); 
    _callback(new PathResult(null, success, _request.Callback)); 
    return; 
} 

RequestPathStartThreadedPathfinding是在一個名爲PathRequestManagerFindPath是一個其他班級稱爲Pathfinder

另一點是,線程不僅僅因爲這樣的錯誤而停止,但仍然以某種方式運行我認爲,因爲在Unity中啓動場景後,我必須殺死taskmanager中的Unity進程,因爲某事被卡住了(當我必須這樣做時,CPU負載總是80%左右) 想到了死鎖但找不到任何東西。

我會很高興,如果有人可以幫助我在這裏,如果你需要對源代碼的更多信息,請隨時問:)

+0

一般來說,你不想爲這種類型的東西大掃蕩線程。更好地使用主線程中的一系列幀的漸進延遲計算 – MickyD

+0

以及如何做到這一點? – Rafiwui

+0

嘗試查找'StartCoroutine'。而且由於Unity的默認協同程序吸引了社區,所以開發了一個非常棒的資源:更有效的協程(免費)等等。 – BrokenBacon

回答

0

所以我發現這個問題由於在Unity forums答案:

我正在研究相同的Grid,因此每個線程都在同一個Nodes上。當我在一個線程中更新算法中的Node,而另一個線程使用相同的Node時,發生了一些不好的事情,結果可以在上面的問題中看到。

我解決了這個問題,克隆每個線程的網格,並在線程擁有的網格上工作。