Advertisement
Guest User

ThreadManager

a guest
Mar 15th, 2015
459
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Threading;
  5. using System.Linq;
  6.  
  7. public class ThreadManager {
  8.  
  9. public static ThreadManager Instance { get; private set; }
  10.  
  11. Timer timer;
  12. Vector3 priorityPos = new Vector3();
  13. List<ChunkThread> runningThreads;
  14. Queue<ChunkThread> queue { get; set; }
  15. object threadLock;
  16. public int maxThreads;
  17. int mutex;
  18.  
  19. static ThreadManager(){
  20. Instance = new ThreadManager();
  21. }
  22.  
  23. public ThreadManager(){
  24.  
  25. //lock
  26. Interlocked.Exchange (ref mutex, 1);
  27.  
  28. //thread queue initialized
  29. queue = new Queue<ChunkThread> (16384);
  30.  
  31. //running and idle threads lists initialized
  32. runningThreads = new List<ChunkThread>();
  33. //maxThreads = 4;
  34.  
  35. //unlock
  36. Interlocked.Exchange (ref mutex, 0);
  37.  
  38. this.timer = new Timer ((obj) => {
  39. ProcessThread ();}, null, 16, 16);
  40. }
  41.  
  42. public void ProcessThread(){
  43. int mval = (int) Interlocked.CompareExchange (ref mutex, 0, 1);
  44. if (mval != 0)
  45. return;
  46.  
  47. lock (queue) {
  48. if (queue.Count>0 && runningThreads.Count<maxThreads){
  49. ChunkThread thread = queue.Dequeue();
  50. runningThreads.Add(thread);
  51.  
  52. if (thread != null){
  53. thread.Start();
  54. }
  55. }
  56. }
  57. }
  58.  
  59. public void AddThread(ChunkThread t){
  60. lock (queue) {
  61. queue.Enqueue(t);
  62. }
  63. }
  64.  
  65. public void RemoveThread(ChunkThread t){
  66. runningThreads.Remove(t);
  67. }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement