Create Mutex Binary Semaphore

semo = semaphore.mutex()

Create and return a new binary semaphore (mutex) object.

Warning

If a Lua error occurs between the semo:wait() and semo:release() then the mutex will be left locked, and Lua may need rebooting and/or the buffer.

Example

If a Lua resource needs to be kept coherent, you can use a mutex to lock access to it:


data = {}
data.mutex = semaphore.mutex()

function Update(the_data, values)
  while not the_data.mutex:wait()
  do
    -- handle loops better...
  end
  the_data.values = util.dct(values) -- deep copy, not reference
  the_data.update_count = (the_data.update_count or 0) + 1
  the_data.mutex:release()
end

function GetValues(the_data)
  while not the_data.mutex:wait()
  do
    -- handle loops better...
  end
  local count, values
  values = util.dct(the_data.values) -- deep copy table
  count = the_data.count
  the_data.mutex:release()
  return count, values
end

In this example, both the values and the count are coherent. Without the mutex, it is possible that GetValues could return a new values and an old count - if it's called in between the updates of Update.