PriorityQueue.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections;
  29. using System.Collections.Generic;
  30. using System.Reflection;
  31. using OpenSim.Framework;
  32. using OpenSim.Framework.Client;
  33. using log4net;
  34. namespace OpenSim.Framework
  35. {
  36. public class PriorityQueue
  37. {
  38. // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  39. public delegate bool UpdatePriorityHandler(ref uint priority, ISceneEntity entity);
  40. /// <summary>
  41. /// Total number of queues (priorities) available
  42. /// </summary>
  43. public const uint NumberOfQueues = 13; // includes immediate queues, m_queueCounts need to be set acording
  44. /// <summary>
  45. /// Number of queuest (priorities) that are processed immediately
  46. /// </summary.
  47. public const uint NumberOfImmediateQueues = 2;
  48. // first queues are immediate, so no counts
  49. private static readonly uint[] m_queueCounts = {0, 0, 8, 8, 5, 4, 3, 2, 1, 1, 1, 1, 1 };
  50. // this is ava, ava, attach, <10m, 20,40,80,160m,320,640,1280, +
  51. private MinHeap<MinHeapItem>[] m_heaps = new MinHeap<MinHeapItem>[NumberOfQueues];
  52. private Dictionary<uint, LookupItem> m_lookupTable;
  53. // internal state used to ensure the deqeues are spread across the priority
  54. // queues "fairly". queuecounts is the amount to pull from each queue in
  55. // each pass. weighted towards the higher priority queues
  56. private uint m_nextQueue = 0;
  57. private uint m_countFromQueue = 0;
  58. private int m_capacity;
  59. private int m_added;
  60. // next request is a counter of the number of updates queued, it provides
  61. // a total ordering on the updates coming through the queue and is more
  62. // lightweight (and more discriminating) than tick count
  63. private UInt64 m_nextRequest = 0;
  64. /// <summary>
  65. /// Lock for enqueue and dequeue operations on the priority queue
  66. /// </summary>
  67. private object m_syncRoot = new object();
  68. public object SyncRoot {
  69. get { return this.m_syncRoot; }
  70. }
  71. #region constructor
  72. public PriorityQueue() : this(MinHeap<MinHeapItem>.DEFAULT_CAPACITY) { }
  73. public PriorityQueue(int capacity)
  74. {
  75. m_capacity = 16;
  76. capacity /= 4;
  77. for (int i = 0; i < m_heaps.Length; ++i)
  78. m_heaps[i] = new MinHeap<MinHeapItem>(capacity);
  79. m_lookupTable = new Dictionary<uint, LookupItem>(m_capacity);
  80. m_nextQueue = NumberOfImmediateQueues;
  81. m_countFromQueue = m_queueCounts[m_nextQueue];
  82. m_added = 0;
  83. }
  84. #endregion Constructor
  85. #region PublicMethods
  86. public void Close()
  87. {
  88. for (int i = 0; i < m_heaps.Length; ++i)
  89. m_heaps[i] = null;
  90. m_heaps = null;
  91. m_lookupTable.Clear();
  92. m_lookupTable = null;
  93. }
  94. /// <summary>
  95. /// Return the number of items in the queues
  96. /// </summary>
  97. public int Count
  98. {
  99. get
  100. {
  101. int count = 0;
  102. for (int i = 0; i < m_heaps.Length; ++i)
  103. count += m_heaps[i].Count;
  104. return count;
  105. }
  106. }
  107. /// <summary>
  108. /// Enqueue an item into the specified priority queue
  109. /// </summary>
  110. public bool Enqueue(uint pqueue, EntityUpdate value)
  111. {
  112. LookupItem lookup;
  113. IHandle lookupH;
  114. UInt64 entry;
  115. uint localid = value.Entity.LocalId;
  116. if (m_lookupTable.TryGetValue(localid, out lookup))
  117. {
  118. lookupH = lookup.Handle;
  119. entry = lookup.Heap[lookupH].EntryOrder;
  120. EntityUpdate up = lookup.Heap[lookupH].Value;
  121. value.Update(lookup.Heap[lookupH].Value);
  122. lookup.Heap.Remove(lookupH);
  123. if((up.Flags & PrimUpdateFlags.CancelKill) != 0)
  124. entry = m_nextRequest++;
  125. pqueue = Util.Clamp<uint>(pqueue, 0, NumberOfQueues - 1);
  126. lookup.Heap = m_heaps[pqueue];
  127. lookup.Heap.Add(new MinHeapItem(pqueue, entry, value), ref lookup.Handle);
  128. m_lookupTable[localid] = lookup;
  129. return true;
  130. }
  131. value.Update();
  132. entry = m_nextRequest++;
  133. ++m_added;
  134. pqueue = Util.Clamp<uint>(pqueue, 0, NumberOfQueues - 1);
  135. lookup.Heap = m_heaps[pqueue];
  136. lookup.Heap.Add(new MinHeapItem(pqueue, entry, value), ref lookup.Handle);
  137. m_lookupTable[localid] = lookup;
  138. return true;
  139. }
  140. public void Remove(List<uint> ids)
  141. {
  142. LookupItem lookup;
  143. foreach (uint localid in ids)
  144. {
  145. if (m_lookupTable.TryGetValue(localid, out lookup))
  146. {
  147. lookup.Heap.Remove(lookup.Handle);
  148. m_lookupTable.Remove(localid);
  149. }
  150. }
  151. if(m_lookupTable.Count == 0 && m_added > 8 * m_capacity)
  152. {
  153. m_lookupTable = new Dictionary<uint, LookupItem>(m_capacity);
  154. m_added = 0;
  155. }
  156. }
  157. /// <summary>
  158. /// Remove an item from one of the queues. Specifically, it removes the
  159. /// oldest item from the next queue in order to provide fair access to
  160. /// all of the queues
  161. /// </summary>
  162. public bool TryDequeue(out EntityUpdate value)
  163. {
  164. // If there is anything in immediate queues, return it first no
  165. // matter what else. Breaks fairness. But very useful.
  166. for (int iq = 0; iq < NumberOfImmediateQueues; iq++)
  167. {
  168. if (m_heaps[iq].Count > 0)
  169. {
  170. MinHeapItem item = m_heaps[iq].RemoveMin();
  171. m_lookupTable.Remove(item.Value.Entity.LocalId);
  172. value = item.Value;
  173. return true;
  174. }
  175. }
  176. // To get the fair queing, we cycle through each of the
  177. // queues when finding an element to dequeue.
  178. // We pull (NumberOfQueues - QueueIndex) items from each queue in order
  179. // to give lower numbered queues a higher priority and higher percentage
  180. // of the bandwidth.
  181. MinHeap<MinHeapItem> curheap = m_heaps[m_nextQueue];
  182. // Check for more items to be pulled from the current queue
  183. if (m_countFromQueue > 0 && curheap.Count > 0)
  184. {
  185. --m_countFromQueue;
  186. MinHeapItem item = curheap.RemoveMin();
  187. m_lookupTable.Remove(item.Value.Entity.LocalId);
  188. value = item.Value;
  189. return true;
  190. }
  191. // Find the next non-immediate queue with updates in it
  192. for (uint i = NumberOfImmediateQueues; i < NumberOfQueues; ++i)
  193. {
  194. m_nextQueue++;
  195. if(m_nextQueue >= NumberOfQueues)
  196. m_nextQueue = NumberOfImmediateQueues;
  197. curheap = m_heaps[m_nextQueue];
  198. if (curheap.Count == 0)
  199. continue;
  200. m_countFromQueue = m_queueCounts[m_nextQueue];
  201. --m_countFromQueue;
  202. MinHeapItem item = curheap.RemoveMin();
  203. m_lookupTable.Remove(item.Value.Entity.LocalId);
  204. value = item.Value;
  205. return true;
  206. }
  207. value = default(EntityUpdate);
  208. if(m_lookupTable.Count == 0 && m_added > 8 * m_capacity)
  209. {
  210. m_lookupTable = new Dictionary<uint, LookupItem>(m_capacity);
  211. m_added = 0;
  212. }
  213. return false;
  214. }
  215. public bool TryOrderedDequeue(out EntityUpdate value)
  216. {
  217. for (int iq = 0; iq < NumberOfQueues; ++iq)
  218. {
  219. MinHeap<MinHeapItem> curheap = m_heaps[iq];
  220. if (curheap.Count > 0)
  221. {
  222. MinHeapItem item = curheap.RemoveMin();
  223. m_lookupTable.Remove(item.Value.Entity.LocalId);
  224. value = item.Value;
  225. return true;
  226. }
  227. }
  228. value = default(EntityUpdate);
  229. if(m_lookupTable.Count == 0 && m_added > 8 * m_capacity)
  230. {
  231. m_lookupTable = new Dictionary<uint, LookupItem>(m_capacity);
  232. m_added = 0;
  233. }
  234. return false;
  235. }
  236. /// <summary>
  237. /// Reapply the prioritization function to each of the updates currently
  238. /// stored in the priority queues.
  239. /// </summary
  240. public void Reprioritize(UpdatePriorityHandler handler)
  241. {
  242. MinHeapItem item;
  243. uint pqueue = 0;
  244. foreach (LookupItem lookup in new List<LookupItem>(m_lookupTable.Values))
  245. {
  246. if (lookup.Heap.TryGetValue(lookup.Handle, out item))
  247. {
  248. if (handler(ref pqueue, item.Value.Entity))
  249. {
  250. // unless the priority queue has changed, there is no need to modify
  251. // the entry
  252. pqueue = Util.Clamp<uint>(pqueue, 0, NumberOfQueues - 1);
  253. if (pqueue != item.PriorityQueue)
  254. {
  255. lookup.Heap.Remove(lookup.Handle);
  256. LookupItem litem = lookup;
  257. litem.Heap = m_heaps[pqueue];
  258. litem.Heap.Add(new MinHeapItem(pqueue, item), ref litem.Handle);
  259. m_lookupTable[item.Value.Entity.LocalId] = litem;
  260. }
  261. }
  262. else
  263. {
  264. // m_log.WarnFormat("[PQUEUE]: UpdatePriorityHandler returned false for {0}",item.Value.Entity.UUID);
  265. lookup.Heap.Remove(lookup.Handle);
  266. m_lookupTable.Remove(item.Value.Entity.LocalId);
  267. }
  268. }
  269. }
  270. }
  271. /// <summary>
  272. /// </summary>
  273. public override string ToString()
  274. {
  275. string s = "";
  276. for (int i = 0; i < NumberOfQueues; i++)
  277. s += String.Format("{0,7} ", m_heaps[i].Count);
  278. return s;
  279. }
  280. #endregion PublicMethods
  281. #region MinHeapItem
  282. private struct MinHeapItem : IComparable<MinHeapItem>
  283. {
  284. private EntityUpdate value;
  285. internal EntityUpdate Value
  286. {
  287. get
  288. {
  289. return value;
  290. }
  291. }
  292. private uint pqueue;
  293. internal uint PriorityQueue
  294. {
  295. get
  296. {
  297. return pqueue;
  298. }
  299. }
  300. private UInt64 entryorder;
  301. internal UInt64 EntryOrder
  302. {
  303. get
  304. {
  305. return entryorder;
  306. }
  307. }
  308. internal MinHeapItem(uint _pqueue, MinHeapItem other)
  309. {
  310. entryorder = other.entryorder;
  311. value = other.value;
  312. pqueue = _pqueue;
  313. }
  314. internal MinHeapItem(uint _pqueue, UInt64 _entryorder, EntityUpdate _value)
  315. {
  316. entryorder = _entryorder;
  317. value = _value;
  318. pqueue = _pqueue;
  319. }
  320. public override string ToString()
  321. {
  322. return String.Format("[{0},{1},{2}]",pqueue,entryorder,value.Entity.LocalId);
  323. }
  324. public int CompareTo(MinHeapItem other)
  325. {
  326. // I'm assuming that the root part of an SOG is added to the update queue
  327. // before the component parts
  328. return Comparer<UInt64>.Default.Compare(this.EntryOrder, other.EntryOrder);
  329. }
  330. }
  331. #endregion
  332. #region LookupItem
  333. private struct LookupItem
  334. {
  335. internal MinHeap<MinHeapItem> Heap;
  336. internal IHandle Handle;
  337. }
  338. #endregion
  339. }
  340. }