Skip to content

Instantly share code, notes, and snippets.

@slact
Created January 12, 2011 18:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slact/776647 to your computer and use it in GitHub Desktop.
Save slact/776647 to your computer and use it in GitHub Desktop.
transaction grouper
local tslice = function(orig, first, last)
local copy = {}
while i=first, last do
table.insert(copy, orig[i])
end
return copy
end
local function transactionize = function(self, transaction_blocks)
local transaction_coroutines = {}
for i,naked_callback in pairs(transaction_blocks) do
table.insert(transaction_coroutines, ccreate(naked_callback))
end
local my_key = self:getKey()
--transaction function
local res, err = redis:transaction({cas=true, watch=self:getKey()}, function(redis)
--WATCH ...
while i<#transaction_coroutines do
local transaction_callback = transaction_coroutines[i]
assert(cresume(transaction_callback, redis, ...))
if cstatus(transaction_callback)~='dead' then
i = i + 1
else
table.remove(transaction_coroutines, i)
end
end
redis:multi()
local queued_commands_offset = {}
while i<#transaction_coroutines do
local transaction_callback = transaction_coroutines[i]
local already_queued = redis:commands_queued()
assert(cresume(transaction_callback))
if cstatus(transaction_callback) ~= 'dead' then
queued_commands_offset[transaction_callback]={ already_queued, redis:commands_queued() }
i = i + 1
else
table.remove(transaction_coroutines, i)
end
end
end)
if not res then return nil, err end
for i, transaction_callback in ipairs(transaction_coroutines) do
cresume(transaction_callback, tslice(res, unpack(queued_commands_offset[transaction_callback])))
--we no longer care about the coroutine's status. we're done.
end
return res
end
@slact
Copy link
Author

slact commented Jan 12, 2011

A transaction block for this function might look like this: https://gist.github.com/776659

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment