Software /
code /
prosody
Comparison
util/async.lua @ 8407:f652e1ea2f69
util.async: Factor out thread check into a function
author | Kim Alvefur <zash@zash.se> |
---|---|
date | Tue, 21 Nov 2017 21:48:14 +0100 |
parent | 8237:f81cd9aaf994 |
child | 8408:b751bee6a829 |
comparison
equal
deleted
inserted
replaced
8406:e39edc6d1523 | 8407:f652e1ea2f69 |
---|---|
1 local log = require "util.logger".init("util.async"); | 1 local log = require "util.logger".init("util.async"); |
2 | |
3 local function checkthread() | |
4 local thread = coroutine.running(); | |
5 if not thread then | |
6 error("Not running in an async context, see https://prosody.im/doc/developers/util/async"); | |
7 end | |
8 return thread; | |
9 end | |
2 | 10 |
3 local function runner_continue(thread) | 11 local function runner_continue(thread) |
4 -- ASSUMPTION: runner is in 'waiting' state (but we don't have the runner to know for sure) | 12 -- ASSUMPTION: runner is in 'waiting' state (but we don't have the runner to know for sure) |
5 if coroutine.status(thread) ~= "suspended" then -- This should suffice | 13 if coroutine.status(thread) ~= "suspended" then -- This should suffice |
6 return false; | 14 return false; |
23 end | 31 end |
24 return true; | 32 return true; |
25 end | 33 end |
26 | 34 |
27 local function waiter(num) | 35 local function waiter(num) |
28 local thread = coroutine.running(); | 36 local thread = checkthread(); |
29 if not thread then | |
30 error("Not running in an async context, see https://prosody.im/doc/developers/util/async"); | |
31 end | |
32 num = num or 1; | 37 num = num or 1; |
33 local waiting; | 38 local waiting; |
34 return function () | 39 return function () |
35 if num == 0 then return; end -- already done | 40 if num == 0 then return; end -- already done |
36 waiting = true; | 41 waiting = true; |
46 end | 51 end |
47 | 52 |
48 local function guarder() | 53 local function guarder() |
49 local guards = {}; | 54 local guards = {}; |
50 return function (id, func) | 55 return function (id, func) |
51 local thread = coroutine.running(); | 56 local thread = checkthread(); |
52 if not thread then | |
53 error("Not running in an async context, see https://prosody.im/doc/developers/util/async"); | |
54 end | |
55 local guard = guards[id]; | 57 local guard = guards[id]; |
56 if not guard then | 58 if not guard then |
57 guard = {}; | 59 guard = {}; |
58 guards[id] = guard; | 60 guards[id] = guard; |
59 log("debug", "New guard!"); | 61 log("debug", "New guard!"); |