global_counter
This crate implements global counters, generic and primitive, which build on thoroughly tested synchronization primitives, namely parking_lot
s Mutex (by default) and the stdlibs atomic types. Faster counters, which trade accuracy for performance, are also available. Refer to the documentation for details.
Usage
Add the following dependency to your Cargo.toml file:
[]
= "0.2.1"
Use the #[macro_use]
annotation when importing, like this:
extern crate global_counter;
If you want to disable using parking_lot
, and instead use the stdlibs Mutex, disable the default features:
[]
= "0.2.1"
= false
Quickstart
Create a counter
use Counter;
use CounterI16;
// Generic
global_counter!;
// If you feel funny, you can also create a generic global counter without a macro.
// Take a look at the implemtation of the macro, it's simply wrapping in a once_cell::sync::Lazy<...>.
// Primitive
static COUNTER_NAME : CounterI16 = new;
Count your counter up
COUNTER_NAME.inc;
Get the value of your counter
// Generic
let val_borrowed = COUNTER_NAME.get_borrowed;
// Or
let val = COUNTER_NAME.get_cloned;
// Primitive
let val = COUNTER_NAME.get;
Example - Primitive counter used for indexing into vec from multiple threads
extern crate global_counter;
use CounterUsize;
use ;
Example - No cloning of counted struct
extern crate global_counter;
use ;
use LinkedList;
use FromIterator;
// Note how this (supposedly) doesn't implement `Clone`.
>);
// Incrementing to us means just inserting another element.
// Some helper methods.
// We create a new global, thread-safe Counter.
// Could also do this in the main fn or wherever.
global_counter!;
Changelog
This library is still being developed. A detailed changelog will be introduced, once a relatively stable state is reached. Treat every version bump as a breaking change.
License
Licensed under either of
- Apache License, Version 2.0, (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.