#channel #concurrent

update_channel

A channel for single updatable values

4 releases

0.1.3 Jan 29, 2021
0.1.2 Jan 29, 2021
0.1.1 Jan 15, 2021
0.1.0 Jan 15, 2021

#181 in Concurrency

25 downloads per month

MIT license

18KB
362 lines

A channel for single updatable values. The Updater can update a shared value and a Receiver can then update it's own internal value.

Example:

    use update_channel::channel_with;
    use std::thread::spawn;

    let (mut receiver, updater) = channel_with(0);
    assert_eq!(*receiver.borrow(), 0);

    spawn(move || {
        updater.update(2).unwrap(); // shared value is 2
        updater.update(12).unwrap(); // shared value is 12
    })
    .join().unwrap();

    // Shared value is 2 but internal value is 0
    assert_eq!(*receiver.borrow(), 0);
    // Update the latest value
    receiver.recv_update().unwrap();
    // Shared value is 12 and internal value 12
    assert_eq!(*receiver.borrow(), 12);

update_channel is distributed under the terms of the MIT license.

See LICENSE for more details


lib.rs:

Single value multiple producer multiple consumer update channel. Both the receiver and channel can be created with the update_channel and update_channel_with functions.

The channels are mostly lock free, multiple readers can access the shared value at the same time. The only way to really block is by calling the borrow_locked method and holding onto the RwLockReadGuard or by having a lot of writes happen at the same time.

The update channel can practically be seen as a single value which can be updated by an updater and then a receiver can update its own internal value with the receive_update method by cloning the new value in its internal buffer. If only a single receiver is used the take_update method is a more efficient alternative to the receive_update method

Example

use update_channel::channel_with;
use std::thread::spawn;

let (mut receiver, updater) = channel_with(0);
assert_eq!(*receiver.borrow(), 0);

spawn(move || {
    updater.update(2).unwrap(); // shared value is 2
    updater.update(12).unwrap(); // shared value is 12
})
.join().unwrap();

// Shared value is 2 but internal value is 0
assert_eq!(*receiver.borrow(), 0);
// Update the latest value
receiver.recv_update().unwrap();
// Shared value is 12 and internal value 12
assert_eq!(*receiver.borrow(), 12);

No runtime deps