MoonGen
 All Files Functions Variables Pages
lock.lua
Go to the documentation of this file.
1 ---------------------------------
2 --- @file lock.lua
3 --- @brief Lock ...
4 --- @todo TODO docu
5 ---------------------------------
6 
7 local mod = {}
8 
9 local ffi = require "ffi"
10 local stp = require "StackTracePlus"
11 
12 ffi.cdef [[
13  struct lock { };
14 
15  struct lock* make_lock();
16  void lock_lock(struct lock* lock);
17  void lock_unlock(struct lock* lock);
18  uint32_t lock_try_lock(struct lock* lock);
19  uint32_t lock_try_lock_for(struct lock* lock, uint32_t us);
20 ]]
21 
22 local C = ffi.C
23 
24 local lock = {}
25 lock.__index = lock
26 
27 function mod:new()
28  return C.make_lock()
29 end
30 
31 function lock:lock()
32  C.lock_lock(self)
33 end
34 
35 function lock:unlock()
36  C.lock_unlock(self)
37 end
38 
39 --- Try to acquire the lock, blocking for max <timeout> microseconds.
40 --- This function does not block if timeout is <= 0.
41 --- This function may fail spuriously, i.e. return early or fail to acquire the lock.
42 --- @param timeout max time to wait in us
43 --- @returns true if the lock was acquired, false otherwise
44 function lock:tryLock(timeout)
45  return C.lock_try_lock_for(self, timeout) == 1
46 end
47 
48 --- Wrap a function call in lock/unlock calls.
49 --- Calling this is equivalent to the following pseudo-code:
50 --- @code
51 --- lock:lock()
52 --- try {
53 --- func(...)
54 --- } finally {
55 --- lock:unlock()
56 --- }
57 --- @endcode
58 --- @param func the function to call
59 --- @param ... arguments passed to the function
60 function lock:__call(func, ...)
61  self:lock()
62  local ok, err = xpcall(func, function(err)
63  return stp.stacktrace(err)
64  end, ...)
65  self:unlock()
66  if not ok then
67  -- FIXME: this output is going to be ugly because it will output the local err as well :>
68  error("caught error in lock-wrapped call, inner error: " .. err, 2)
69  end
70 end
71 
72 ffi.metatype("struct lock", lock)
73 
74 return mod
75 
local ffi
low-level dpdk wrapper
Definition: dpdkc.lua:6
function lock tryLock(timeout)
Try to acquire the lock, blocking for max <timeout> microseconds.
function lock __call(func,...)
Wrap a function call in lock/unlock calls.
local mod
high-level dpdk wrapper
Definition: dpdk.lua:6