• Stars
    star
    53
  • Rank 533,227 (Top 11 %)
  • Language
    Erlang
  • License
    MIT License
  • Created about 5 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

BEAM friendly spinlocks for Elixir/Erlang

sleeplocks

Build Status Hex.pm Version Documentation

This library is designed to provide simple locking mechanisms in Erlang/Elixir, similar to how spinlocks work in other languages - except using messages to communicate locking.

This is useful for libraries which require lock synchronization, without having to roll your own (however simple). Locks can be held by arbitrary numbers of process, making it possible to implement various throttling mechanisms.

Best of all, this library is tiny! It builds upon basic OTP principles to implement lock behaviour via simple processes and message passing.

Installation

Rebar

Follow the instructons found here to configure your Rebar setup to use Hex as a dependency source, then you can grab it directly:

{deps,[
  % pulls the latest version
  sleeplocks,
  % to pull the latest version from github
  {sleeplocks, {git, "git://github.com/whitfin/sleeplocks.git"}}
]}.

Mix

To install it for your project, you can pull it directly from Hex. Rather than use the version shown below, you can use the latest version from Hex (shown at the top of this README).

def deps do
  [{:sleeplocks, "~> 1.0"}]
end

Usage

Snippets below contain sample usage in both Erlang and Elixir, and cover most of the small API space offered by sleeplocks. For a more complete example, scroll down!

Erlang

% create a new single lock (with a name)
1> sleeplocks:new(1, [{name, {local, my_lock}}]).
{ok,<0.179.0>}

% take ownership of the lock
2> sleeplocks:acquire(my_lock).
ok

% release the current hold on a lock
3> sleeplocks:release(my_lock).
ok

% attempt to acquire a lock (which will succeed)
4> sleeplocks:attempt(my_lock).
ok

% now that it's taken, other attempts will fail
5> sleeplocks:attempt(my_lock).
{error,unavailable}

% release the lock again
6> sleeplocks:release(my_lock).
ok

% handle acquisition and locking automatically
7> sleeplocks:execute(my_lock, fun() ->
7>   3
7> end).
3

Elixir

# create a new single lock (with a name)
iex(1)> :sleeplocks.new(1, [ name: :my_lock ])
{:ok, #PID<0.179.0>}

# take ownership of the lock
iex(2)> :sleeplocks.acquire(:my_lock)
:ok

# release the current hold on a lock
iex(3)> :sleeplocks.release(:my_lock)
:ok

# attempt to acquire a lock (which will succeed)
iex(4)> :sleeplocks.attempt(:my_lock)
:ok

# now that it's taken, other attempts will fail
iex(5)> :sleeplocks.attempt(:my_lock)
{:error, :unavailable}

# release the lock again
iex(6)> :sleeplocks.release(:my_lock)
:ok

# handle acquisition and locking automatically
iex(7)> :sleeplocks.execute(:my_lock, fn ->
iex(7)>   3
iex(7)> end)
3

Examples

This example is in Elixir, but it should be fairly understandable for those coming from both languages. It simply spawns 6 processes which each attempt to hold a lock for 10 seconds. As the lock is created with only 2 slots, this runs for 30 seconds and 2 of our spawned tasks can hold the lock at any given time.

# First create a new lock, with 2 slots only
{:ok, ref} = :sleeplocks.new(2)

# Then spawn 6 tasks, which each just sleep for 10 seconds
# after acquiring the lock. This means that 2 processes will
# acquire a lock and then release after 10 seconds. This
# will repeat 3 times (6 / 2) until 30 seconds are up.
for idx <- 1..6 do
  Task.start(fn ->
    :sleeplocks.execute(ref, fn ->
      IO.puts("Locked #{idx}")
      Process.sleep(10_000)
      IO.puts("Releasing #{idx}")
    end)
  end)
end

More Repositories

1

cachex

A powerful caching library for Elixir with support for transactions, fallbacks and expirations
Elixir
1,441
star
2

runiq

An efficient way to filter duplicate lines from input, à la uniq.
Rust
203
star
3

local-cluster

Easy local cluster creation for Elixir to aid in unit testing
Elixir
193
star
4

eternal

Keep your ETS tables running forever using bouncing GenServers
Elixir
84
star
5

bytelines

Read input lines as byte slices for high efficiency
Rust
61
star
6

jen

A fast utility to generate fake/test documents based on a template
Rust
59
star
7

s3-utils

Utilities and tools based around Amazon S3 to provide convenience APIs in a CLI
Rust
53
star
8

stash

A small and user-friendly ETS wrapper for caching in Elixir
Elixir
52
star
9

limber

A simple (but quick) tool for backing up Elasticsearch documents
Rust
50
star
10

retainer

Minimal async cache in Rust with support for key expirations
Rust
49
star
11

s3-meta

Gather metadata about your S3 buckets
Rust
49
star
12

tiny

A small, fast and fully compliant JSON parser in Elixir
Elixir
47
star
13

s3-concat

Concatenate Amazon S3 files remotely using flexible patterns
Rust
38
star
14

usher

Parameterized routing for generic resources in Rust
Rust
37
star
15

efflux

Easy Hadoop Streaming and MapReduce interfaces in Rust
Rust
34
star
16

siphash-java

SipHash in Java; zero-allocation and streaming implementations
Java
29
star
17

expool

Extremely simple Process pooling and task submission in Elixir
Elixir
25
star
18

vessel

Elixir MapReduce interfaces with Hadoop Streaming integration
Elixir
23
star
19

neek

A simple way to filter duplicate lines from a list, à la uniq.
JavaScript
22
star
20

it.each

A Mocha extension allowing for test looping with (a)sync calls
JavaScript
21
star
21

hypex

Fast HyperLogLog implementation for Elixir/Erlang
Elixir
20
star
22

siphash-elixir

An Elixir implementation of the SipHash cryptographic hash family
Elixir
18
star
23

detox

Quickly clean up your development directories before backups
Rust
18
star
24

RSSDemo

A simple demonstration of an RSS reader for Android.
Java
16
star
25

capture-console

Simple and easy stdio capture for Node.js
JavaScript
16
star
26

sentix

A cross-platform file watcher for Elixir based on fswatch.
Elixir
15
star
27

unsafe

Generate unsafe (!) bindings for Elixir functions
Elixir
12
star
28

siphash-cpp

A small C++ implementation of SipHash using a streaming algorithm with CLI
C++
12
star
29

dot-notes-js

Simple dot/bracket notation parsing/conversion for JSON
JavaScript
12
star
30

jumper

Jump consistent hash implementation in Elixir (without NIFs)
Elixir
12
star
31

rabbitmq-delimiter-exchange

Performant RabbitMQ exchange with support for multiple routing keys per message
Makefile
12
star
32

deppie

Elixir's coolest deprecation logger
Elixir
11
star
33

pre_plug

Guarantee your Elixir Plugs execute on every request
Elixir
9
star
34

docker-geoipupdate

Minimal container for updating GeoIP databases on your host system
Shell
8
star
35

global-flags

Write once global flags for Erlang and Elixir.
Erlang
8
star
36

kscrash-converter

Converts KSCrash JSON output to Apple format
JavaScript
7
star
37

gen_delegate

Macro based delegates for GenServer functions
Elixir
7
star
38

dot-notes-elixir

Simple dot/bracket notation parsing/conversion for Maps/Lists
Elixir
7
star
39

andrest

Basic REST protocol implementation for Android.
Java
6
star
40

phoenix_mongo

An example of setting up Phoenix to use the unofficial Mongo Ecto library
CSS
6
star
41

rabbitmq-manager

A RabbitMQ monitoring system written in NodeJS.
JavaScript
6
star
42

elasticsearch-bulk-operator

Elasticsearch Bulk API bindings using the Java REST client
Java
5
star
43

lowdb-titanium-adapter

Titanium SDK adapter for the LowDB embedded database
JavaScript
4
star
44

loki-titanium-adapter

Titanium SDK adapter for the LokiJS embedded database
JavaScript
4
star
45

dot-notes-java

Jackson JSON flattening/iteration/inflation using simple key parsing
Java
4
star
46

siphash-c

A C (89) implementation of the SipHash cryptographic hash family, using a single pass algorithm
C
3
star
47

child-spec-compat

Compatibility macros for Elixir v1.5+ child specifications
Elixir
3
star
48

global-lazy

Lazy global initialization for Elixir, without state
Elixir
3
star
49

argle

Convenient argument shifting because you know you need it
JavaScript
2
star
50

dropwizard-environment-substitutor

Global environment overrides for Dropwizard configuration
Java
2
star
51

native-hashset

A native HashSet implementation for Node.js and io.js.
C++
2
star
52

luger

Handy logging plug for Elixir with IP and status support
Elixir
2
star
53

dottie

A small library for dealing with JSON dot notation.
Java
2
star
54

dep-validate

Dependency verification for npm packages with Gulp support
JavaScript
1
star
55

archive_bundle

A small task to bundle dependencies into an archive build in Elixir
Elixir
1
star
56

granular-logger

A Winston wrapper to allow time-based log files
JavaScript
1
star
57

noddle

Simple loading of the current project workspace into a REPL
JavaScript
1
star
58

expansion-js

Simple library for NodeJS to expand (and make it easier to expand) the functionality of objects
JavaScript
1
star
59

neps

Node.js REPL with package installation and automatic loading support
JavaScript
1
star
60

appddl

Extremely small CLI tool used to update agent archives from AppDynamics
Rust
1
star
61

svn-to-git

Scripts to convert a Subversion repository to Git.
Shell
1
star
62

json-output-format

JSON output formats for Hadoop MapReduce jobs
Java
1
star
63

projects

A collection of notes and whatnot in regards to either planned or existing projects
JavaScript
1
star
64

waterline-express-example

A base MVC layout using Waterline and Express
JavaScript
1
star