counter_safe
counter_safe
Thread safe counters:
- CounterSafe::Shared -- e.g.: global shared counters
- CounterSafe::Exclusive -- e.g.: class-local exclusive counters
Based on and with much thanks to: https://itnext.io/comparing-crystals-concurrency-with-that-of-go-part-ii-89049701b1a5
Installation
-
Add the dependency to your
shard.yml
:dependencies: counter_safe: github: your-github-user/counter_safe
-
Run
shards install
... orshards install --ignore-crystal-version
Usage
require "counter_safe"
Example Usage:
-
Shared counters
cs1 = CounterSafe::Shared.new cs2 = CounterSafe::Shared.new (1..1000).each { rand < 0.25 ? spawn cs1.inc("someKey") : spawn cs2.inc("someKey") } sleep 1.second puts cs1.value("someKey") puts cs2.value("someKey") #=> Should be the same as 'cs1.value("someKey")'
-
Exclusive counters
ce1 = CounterSafe::Exclusive.new ce2 = CounterSafe::Exclusive.new (1..1000).each { rand < 0.25 ? spawn ce1.inc("someKey") : spawn ce2.inc("someKey") } puts ce1.value("someKey") puts ce2.value("someKey") #=> Should be DIFFERENT than as 'cs1.value("someKey")'
See also API doc's at: https://drhuffman12.github.io/counter_safe
Contributing
- Fork it (https://github.com/your-github-user/counter_safe/fork)
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request
Contributors
- Daniel Huffman - creator and maintainer