PriorityQueue.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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 = 12; // 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};
  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 = capacity;
  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. value.Update(lookup.Heap[lookupH].Value);
  121. lookup.Heap.Remove(lookupH);
  122. }
  123. else
  124. {
  125. entry = m_nextRequest++;
  126. ++m_added;
  127. }
  128. pqueue = Util.Clamp<uint>(pqueue, 0, NumberOfQueues - 1);
  129. lookup.Heap = m_heaps[pqueue];
  130. lookup.Heap.Add(new MinHeapItem(pqueue, entry, value), ref lookup.Handle);
  131. m_lookupTable[localid] = lookup;
  132. return true;
  133. }
  134. public void Remove(List<uint> ids)
  135. {
  136. LookupItem lookup;
  137. foreach (uint localid in ids)
  138. {
  139. if (m_lookupTable.TryGetValue(localid, out lookup))
  140. {
  141. lookup.Heap.Remove(lookup.Handle);
  142. m_lookupTable.Remove(localid);
  143. }
  144. }
  145. if(m_lookupTable.Count == 0 && m_added > 8 * m_capacity)
  146. {
  147. m_lookupTable = new Dictionary<uint, LookupItem>(m_capacity);
  148. m_added = 0;
  149. }
  150. }
  151. /// <summary>
  152. /// Remove an item from one of the queues. Specifically, it removes the
  153. /// oldest item from the next queue in order to provide fair access to
  154. /// all of the queues
  155. /// </summary>
  156. public bool TryDequeue(out EntityUpdate value, out Int32 timeinqueue)
  157. {
  158. // If there is anything in immediate queues, return it first no
  159. // matter what else. Breaks fairness. But very useful.
  160. for (int iq = 0; iq < NumberOfImmediateQueues; iq++)
  161. {
  162. if (m_heaps[iq].Count > 0)
  163. {
  164. MinHeapItem item = m_heaps[iq].RemoveMin();
  165. m_lookupTable.Remove(item.Value.Entity.LocalId);
  166. timeinqueue = Util.EnvironmentTickCountSubtract(item.EntryTime);
  167. value = item.Value;
  168. return true;
  169. }
  170. }
  171. // To get the fair queing, we cycle through each of the
  172. // queues when finding an element to dequeue.
  173. // We pull (NumberOfQueues - QueueIndex) items from each queue in order
  174. // to give lower numbered queues a higher priority and higher percentage
  175. // of the bandwidth.
  176. MinHeap<MinHeapItem> curheap = m_heaps[m_nextQueue];
  177. // Check for more items to be pulled from the current queue
  178. if (m_countFromQueue > 0 && curheap.Count > 0)
  179. {
  180. --m_countFromQueue;
  181. MinHeapItem item = curheap.RemoveMin();
  182. m_lookupTable.Remove(item.Value.Entity.LocalId);
  183. timeinqueue = Util.EnvironmentTickCountSubtract(item.EntryTime);
  184. value = item.Value;
  185. return true;
  186. }
  187. // Find the next non-immediate queue with updates in it
  188. for (uint i = NumberOfImmediateQueues; i < NumberOfQueues; ++i)
  189. {
  190. m_nextQueue++;
  191. if(m_nextQueue >= NumberOfQueues)
  192. m_nextQueue = NumberOfImmediateQueues;
  193. curheap = m_heaps[m_nextQueue];
  194. if (curheap.Count == 0)
  195. continue;
  196. m_countFromQueue = m_queueCounts[m_nextQueue];
  197. --m_countFromQueue;
  198. MinHeapItem item = curheap.RemoveMin();
  199. m_lookupTable.Remove(item.Value.Entity.LocalId);
  200. timeinqueue = Util.EnvironmentTickCountSubtract(item.EntryTime);
  201. value = item.Value;
  202. return true;
  203. }
  204. timeinqueue = 0;
  205. value = default(EntityUpdate);
  206. if(m_lookupTable.Count == 0 && m_added > 8 * m_capacity)
  207. {
  208. m_lookupTable = new Dictionary<uint, LookupItem>(m_capacity);
  209. m_added = 0;
  210. }
  211. return false;
  212. }
  213. public bool TryOrderedDequeue(out EntityUpdate value, out Int32 timeinqueue)
  214. {
  215. MinHeap<MinHeapItem> curheap;
  216. for (int iq = 0; iq < NumberOfQueues; ++iq)
  217. {
  218. curheap = m_heaps[iq];
  219. if (curheap.Count > 0)
  220. {
  221. MinHeapItem item = curheap.RemoveMin();
  222. m_lookupTable.Remove(item.Value.Entity.LocalId);
  223. timeinqueue = Util.EnvironmentTickCountSubtract(item.EntryTime);
  224. value = item.Value;
  225. return true;
  226. }
  227. }
  228. timeinqueue = 0;
  229. value = default(EntityUpdate);
  230. if(m_lookupTable.Count == 0 && m_added > 8 * m_capacity)
  231. {
  232. m_lookupTable = new Dictionary<uint, LookupItem>(m_capacity);
  233. m_added = 0;
  234. }
  235. return false;
  236. }
  237. /// <summary>
  238. /// Reapply the prioritization function to each of the updates currently
  239. /// stored in the priority queues.
  240. /// </summary
  241. public void Reprioritize(UpdatePriorityHandler handler)
  242. {
  243. MinHeapItem item;
  244. foreach (LookupItem lookup in new List<LookupItem>(m_lookupTable.Values))
  245. {
  246. if (lookup.Heap.TryGetValue(lookup.Handle, out item))
  247. {
  248. uint pqueue = item.PriorityQueue;
  249. uint localid = item.Value.Entity.LocalId;
  250. if (handler(ref pqueue, item.Value.Entity))
  251. {
  252. // unless the priority queue has changed, there is no need to modify
  253. // the entry
  254. pqueue = Util.Clamp<uint>(pqueue, 0, NumberOfQueues - 1);
  255. if (pqueue != item.PriorityQueue)
  256. {
  257. lookup.Heap.Remove(lookup.Handle);
  258. LookupItem litem = lookup;
  259. litem.Heap = m_heaps[pqueue];
  260. litem.Heap.Add(new MinHeapItem(pqueue, item), ref litem.Handle);
  261. m_lookupTable[localid] = litem;
  262. }
  263. }
  264. else
  265. {
  266. // m_log.WarnFormat("[PQUEUE]: UpdatePriorityHandler returned false for {0}",item.Value.Entity.UUID);
  267. lookup.Heap.Remove(lookup.Handle);
  268. m_lookupTable.Remove(localid);
  269. }
  270. }
  271. }
  272. }
  273. /// <summary>
  274. /// </summary>
  275. public override string ToString()
  276. {
  277. string s = "";
  278. for (int i = 0; i < NumberOfQueues; i++)
  279. s += String.Format("{0,7} ",m_heaps[i].Count);
  280. return s;
  281. }
  282. #endregion PublicMethods
  283. #region MinHeapItem
  284. private struct MinHeapItem : IComparable<MinHeapItem>
  285. {
  286. private EntityUpdate value;
  287. internal EntityUpdate Value
  288. {
  289. get
  290. {
  291. return value;
  292. }
  293. }
  294. private uint pqueue;
  295. internal uint PriorityQueue
  296. {
  297. get
  298. {
  299. return pqueue;
  300. }
  301. }
  302. private Int32 entrytime;
  303. internal Int32 EntryTime
  304. {
  305. get
  306. {
  307. return entrytime;
  308. }
  309. }
  310. private UInt64 entryorder;
  311. internal UInt64 EntryOrder
  312. {
  313. get
  314. {
  315. return entryorder;
  316. }
  317. }
  318. internal MinHeapItem(uint _pqueue, MinHeapItem other)
  319. {
  320. entrytime = other.entrytime;
  321. entryorder = other.entryorder;
  322. value = other.value;
  323. pqueue = _pqueue;
  324. }
  325. internal MinHeapItem(uint _pqueue, UInt64 _entryorder, EntityUpdate _value)
  326. {
  327. entrytime = Util.EnvironmentTickCount();
  328. entryorder = _entryorder;
  329. value = _value;
  330. pqueue = _pqueue;
  331. }
  332. public override string ToString()
  333. {
  334. return String.Format("[{0},{1},{2}]",pqueue,entryorder,value.Entity.LocalId);
  335. }
  336. public int CompareTo(MinHeapItem other)
  337. {
  338. // I'm assuming that the root part of an SOG is added to the update queue
  339. // before the component parts
  340. return Comparer<UInt64>.Default.Compare(this.EntryOrder, other.EntryOrder);
  341. }
  342. }
  343. #endregion
  344. #region LookupItem
  345. private struct LookupItem
  346. {
  347. internal MinHeap<MinHeapItem> Heap;
  348. internal IHandle Handle;
  349. }
  350. #endregion
  351. }
  352. }