Skip to content

Commit

Permalink
Add set-capacity API
Browse files Browse the repository at this point in the history
  • Loading branch information
x0id committed Feb 26, 2024
1 parent 1185069 commit c2f4757
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
30 changes: 29 additions & 1 deletion c_src/sema_nif.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,11 @@ struct sema {

sema(unsigned n) : cnt(0), dead_counter(0), max(n) {}

ERL_NIF_TERM set_capacity(unsigned n) {
max = n;
return atom_ok;
}

ERL_NIF_TERM info(ErlNifEnv *env) {
ERL_NIF_TERM keys[] = {atom_dead, atom_cnt, atom_max};
ERL_NIF_TERM vals[] = {
Expand Down Expand Up @@ -356,14 +361,37 @@ release(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) {
return res->release(env, pid, n);
}

static ERL_NIF_TERM
set_capacity(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) {
if (argc != 2)
return enif_make_badarg(env);

sema *res = nullptr;
if (!enif_get_resource(env, argv[0], SEMA, (void **)&res))
return enif_make_badarg(env);

if (res == nullptr)
return enif_make_badarg(env);

unsigned n = 1;
if (enif_is_number(env, argv[1]))
enif_get_uint(env, argv[1], &n);
else
return enif_make_badarg(env);

return n > 0 ? res->set_capacity(n) : enif_make_badarg(env);
}

static ErlNifFunc nif_funcs[] = {
{"create", 1, create},
{"info", 1, info},
{"acquire", 1, acquire},
{"acquire", 2, acquire},
{"release", 1, release},
{"release", 2, release},
{"release", 3, release}
{"release", 3, release},
{"release", 3, release},
{"set_capacity", 2, set_capacity}
};

ERL_NIF_INIT(sema_nif, nif_funcs, &load, nullptr, nullptr, nullptr);
10 changes: 8 additions & 2 deletions src/sema_nif.erl
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
acquire/2,
release/1,
release/2,
release/3
release/3,
set_capacity/2
]).

-nifs([
Expand All @@ -17,7 +18,8 @@
acquire/2,
release/1,
release/2,
release/3
release/3,
set_capacity/2
]).

-on_load(init/0).
Expand Down Expand Up @@ -76,6 +78,10 @@ release(_, _) -> not_loaded(?LINE).
-spec release(Semaphore :: sema_ref(), Cnt :: pos_integer(), Pid :: pid()) -> Ret :: release_ret().
release(_, _, _) -> not_loaded(?LINE).

% set (update) semaphore capacity
-spec set_capacity(Semaphore :: sema_ref(), Cnt :: pos_integer()) -> ok.
set_capacity(_, _) -> not_loaded(?LINE).

% internal
init() ->
SoName =
Expand Down

0 comments on commit c2f4757

Please sign in to comment.