Advertisement
Guest User

Untitled

a guest
Oct 13th, 2019
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. using System;
  4. using System.Threading;
  5.  
  6. namespace SkinnedDecals {
  7.  
  8. public class ThreadPooler : MonoBehaviour {
  9.  
  10. private static bool initialized = false;
  11.  
  12. public static int totalThreads = 8;
  13. private static int numThreads = 0;
  14.  
  15. private List<Action> actions = new List<Action>();
  16. private List<Action> currentActions = new List<Action>();
  17.  
  18. #region Instance
  19.  
  20. private static ThreadPooler instance;
  21. public static ThreadPooler Instance {
  22. get {
  23. Initialize();
  24. return instance;
  25. }
  26. }
  27.  
  28. void OnDestroy() {
  29. if(instance == this) {
  30. initialized = false;
  31. instance = null;
  32. }
  33. }
  34.  
  35. #endregion
  36.  
  37. #region Initialization
  38.  
  39. void Awake() {
  40. instance = this;
  41. initialized = true;
  42. }
  43.  
  44. static void Initialize() {
  45. if(!initialized) {
  46. if(!Application.isPlaying)
  47. return;
  48.  
  49. initialized = true;
  50.  
  51. GameObject go = new GameObject("ThreadPooler");
  52. instance = go.AddComponent<ThreadPooler>();
  53. }
  54.  
  55. }
  56.  
  57. #endregion
  58.  
  59. #region Runtime
  60.  
  61. public static void RunOnMainThread(Action action) {
  62. lock(Instance.actions) {
  63. Instance.actions.Add(action);
  64. }
  65. }
  66.  
  67. public static Thread RunOnThread(Action action) {
  68. Initialize();
  69.  
  70. while(numThreads >= totalThreads) {
  71. Thread.Sleep(1);
  72. }
  73.  
  74. Interlocked.Increment(ref numThreads);
  75. ThreadPool.QueueUserWorkItem(RunAction, action);
  76.  
  77. return null;
  78. }
  79.  
  80. private static void RunAction(object action) {
  81. try {
  82. ((Action)action)();
  83. } catch(Exception e) {
  84. Debug.LogError("Exception while trying to run action: " + e.Message + '\n' + e.StackTrace);
  85. } finally {
  86. Interlocked.Decrement(ref numThreads);
  87. }
  88.  
  89. }
  90.  
  91. void Update() {
  92. lock(actions) {
  93. currentActions.Clear();
  94. currentActions.AddRange(actions);
  95. actions.Clear();
  96. }
  97. for(int i = 0; i < currentActions.Count; i++)
  98. currentActions[i]();
  99. }
  100.  
  101. #endregion
  102. }
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement