Advertisement
Guest User

Untitled

a guest
Jun 9th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. if Citizen and Citizen.CreateThread then
  2. CreateThread = Citizen.CreateThread
  3. end
  4.  
  5. Async = {}
  6.  
  7. function Async.parallel(tasks, cb)
  8.  
  9. if #tasks == 0 then
  10. cb({})
  11. return
  12. end
  13.  
  14. local remaining = #tasks
  15. local results = {}
  16.  
  17. for i=1, #tasks, 1 do
  18.  
  19. CreateThread(function()
  20.  
  21. tasks[i](function(result)
  22.  
  23. table.insert(results, result)
  24.  
  25. remaining = remaining - 1;
  26.  
  27. if remaining == 0 then
  28. cb(results)
  29. end
  30.  
  31. end)
  32.  
  33. end)
  34.  
  35. end
  36.  
  37. end
  38.  
  39. function Async.parallelLimit(tasks, limit, cb)
  40.  
  41. if #tasks == 0 then
  42. cb({})
  43. return
  44. end
  45.  
  46. local remaining = #tasks
  47. local running = 0
  48. local queue = {}
  49. local results = {}
  50.  
  51. for i=1, #tasks, 1 do
  52. table.insert(queue, tasks[i])
  53. end
  54.  
  55. local function processQueue()
  56.  
  57. if #queue == 0 then
  58. return
  59. end
  60.  
  61. while running < limit and #queue > 0 do
  62.  
  63. local task = table.remove(queue, 1)
  64.  
  65. running = running + 1
  66.  
  67. task(function(result)
  68.  
  69. table.insert(results, result)
  70.  
  71. remaining = remaining - 1;
  72. running = running - 1
  73.  
  74. if remaining == 0 then
  75. cb(results)
  76. end
  77.  
  78. end)
  79.  
  80. end
  81.  
  82. CreateThread(processQueue)
  83.  
  84. end
  85.  
  86. processQueue()
  87.  
  88. end
  89.  
  90. function Async.series(tasks, cb)
  91. Async.parallelLimit(tasks, 1, cb)
  92. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement