- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 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
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
%% Note: set and unset are not thread-safe.
-spec set(key(), value()) -> ok.
set(Key, Value) ->
    case ets:lookup(?status_tab, Key) of
        [{_, {set, _OldValue}}] ->
            ets:insert(?status_tab, {Key, {set, Value}});
        [{_, {unset, Pid}}] ->
            MRef = monitor(process, Pid),
            Pid ! {set, Value},
            receive
                {'DOWN', MRef, _, _, _} -> ok
            end;
        [] ->
            case ets:insert_new(?status_tab, {Key, {set, Value}}) of
                true  ->
                    ok;
                false ->
                    set(Key, Value)
            end
    end,
    ok.
-spec unset(key()) -> ok.
unset(Key) ->
    case ets:lookup(?status_tab, Key) of
        [{_, {set, _OldValue}}] -> ets:delete(?status_tab, Key);
        _                       -> ok
    end,
    ok.
-spec read(key()) -> value().
read(Key) ->
    case read_or_wait(Key) of
        {set, Value} ->
            Value;
        {wait, MRef} ->
            receive
                {'DOWN', MRef, _, _, {cvar_set, Value}} ->
                    Value;
                {'DOWN', MRef, _, _, noproc} ->
                    read(Key)
            end
    end.
-spec read_or_wait(key()) -> {set, value()} | {wait, reference()}.
read_or_wait(Key) ->
    case ets:lookup(?status_tab, Key) of
        [] ->
            {Pid, MRef} = spawn_monitor(?MODULE, waker_entrypoint, [Key, self()]),
            receive
                {Pid, proceed} ->
                    {wait, MRef};
                {'DOWN', MRef, _, _, Reason} ->
                    cvar_retry = Reason,
                    read_or_wait(Key)
            end;
        [{_, {set, Val}}] ->
            {set, Val};
        [{_, {unset, Pid}}] ->
            {wait, monitor(process, Pid)}
    end.
-spec waker_entrypoint(key(), pid()) -> no_return().
waker_entrypoint(Key, Parent) ->
    case ets_insert_new({Key, {unset, self()}}) of
        false ->
            exit(cvar_retry);
        true ->
            Parent ! {self(), proceed},
            receive
                {set, Value} ->
                    ets_insert({Key, {set, Value}}),
                    exit({cvar_set, Value})
            end
    end.