Advertisement
TheIncgi

Thread Safety

Sep 30th, 2019
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.51 KB | None | 0 0
  1. local threads = {}
  2. local mutex = newMutex("threadSafetyExample")
  3. local numThreads = 10
  4. local eachAdd = 1000
  5.  
  6. sharedTotal = 0
  7.  
  8. local function safe()
  9.   log("&7Started thread")
  10.   sleep(150) --time for all threads to start up
  11.   for i = 1, eachAdd do
  12.     mutex.lock() --start of sensitive code
  13.     sharedTotal = sharedTotal + 1
  14.     mutex.unlock() --end of sensitive code
  15.   end
  16.   log("&7Thread done")
  17. end
  18.  
  19. local function unsafe()
  20.   log("&7Started thread")
  21.   sleep(250) --time for all threads to start up
  22.   for i = 1, eachAdd do
  23.     sharedTotal = sharedTotal + 1
  24.   end
  25.   log("&8Thread done")
  26. end
  27.  
  28. local function makeThreads( withFunc )
  29.   for i = 1, numThreads do
  30.     threads[#threads+1] = thread.new( withFunc )
  31.   end
  32. end
  33.  
  34. local function startThreads()
  35.   for i=1, #threads do
  36.     threads[i].start()
  37.   end
  38.  
  39.   while true do
  40.     local isOneRunning = false
  41.     for i=1, #threads do
  42.       isOneRunning = isOneRunning or (threads[i].getStatus()~="done")
  43.     end
  44.     if not isOneRunning then break end
  45.   end
  46. end
  47.  
  48. local function showResult()
  49.   log(string.format("<&aExpected&f, &6Result&f> <&a%d&f, &6%d&f>",
  50.   numThreads*eachAdd,
  51.   sharedTotal
  52. ))
  53. end
  54.  
  55.  
  56. log("Choose example: &a&B&FSAFE&f or &c&B&FUNSAFE",
  57.   function() --safe example
  58.     threads = {}
  59.     sharedTotal = 0
  60.     makeThreads( safe )
  61.     startThreads()
  62.     showResult()
  63.   end,
  64.   function() --unsafe example
  65.     threads = {}
  66.     sharedTotal = 0
  67.     makeThreads( unsafe )
  68.     startThreads()
  69.     showResult()
  70.   end
  71. )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement