Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

decrease-max-fix #7

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions lib/semaphore.ex
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,31 @@ defmodule Semaphore do

@doc """
Acquire a semaphore, incrementing the internal count by one.

The semaphore's `name` can be any Elixir value. The `max` count for the semaphore is passed on
every `acquire` call. If the `max` is increased, the semaphore's count is preserved. If the
`max` is decreased to a value lower than the current count, the count will be set to the new
`max`.

## Example:

iex> Semaphore.acquire(:sem, 2)
true
iex> Semaphore.acquire(:sem, 2)
true
iex> Semaphore.acquire(:sem, 2)
false
iex> Semaphore.acquire(:sem, 3)
true
iex> Semaphore.acquire(:sem, 1)
false
iex> Semaphore.count(:sem)
1
"""
@spec acquire(term, integer) :: boolean
def acquire(name, max) do
case ETS.update_counter(@table, name, [{2, 0}, {2, 1, max, max}], {name, 0}) do
[^max, _] -> false
_ -> true
[old_val, new_val] -> old_val < new_val
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Annotation: This is the main fix.

As long as the old_val is less than the new_val then we know that we have acquired a lock successfully, whether you are incrementing the max, decrementing the max, or leaving it the same.

end
end

Expand Down
8 changes: 8 additions & 0 deletions test/semaphore_test.exs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
defmodule SemaphoreTest do
use ExUnit.Case, async: false
doctest Semaphore

setup do
Semaphore.reset(:foo)
Expand Down Expand Up @@ -33,6 +34,13 @@ defmodule SemaphoreTest do
assert Semaphore.acquire(:foo, 3) == true
end

test "decrease max" do
assert Semaphore.acquire(:foo, 2) == true
assert Semaphore.acquire(:foo, 2) == true
assert Semaphore.acquire(:foo, 2) == false
assert Semaphore.acquire(:foo, 1) == false
end

test "call" do
assert Semaphore.call(:foo, 1, fn -> :bar end) == :bar
assert Semaphore.count(:foo) == 0
Expand Down