aboutsummaryrefslogtreecommitdiff
path: root/fastnn/threads/test/test-threads-async.lua
blob: 68bcd35dca056ffb6337d9b902b76a83c250932f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
local threads = require 'threads'

local nthread = 4
local njob = 100

local pool = threads.Threads(
   nthread,
   function(threadid)
      print('starting a new thread/state number ' .. threadid)
   end
)


local jobid = 0
local result -- DO NOT put this in get
local function get()
   
   -- fill up the queue as much as we can
   -- this will not block
   while jobid < njob and pool:acceptsjob() do
      jobid = jobid + 1
      
      pool:addjob(
         function(jobid)
            print(string.format('thread ID %d is performing job %d', __threadid, jobid))
            return string.format("job output from job %d", jobid)
         end,

         function(jobres)
            result = jobres
         end,

         jobid
      )
   end

   -- is there still something to do?
   if pool:hasjob() then
      pool:dojob() -- yes? do it!
      if pool:haserror() then -- check for errors
         pool:synchronize() -- finish everything and throw error
      end
      return result
   end

end

local jobdone = 0
repeat   
   -- get something asynchronously
   local res = get()
   
   -- do something with res (if any)
   if res then
      print(res)
      jobdone = jobdone + 1
   end
   
until not res -- until there is nothing remaining

assert(jobid == 100)
assert(jobdone == 100)

print('PASSED')

pool:terminate()