Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from a channel or timeout?

With Rust 1.9, I'd like to read from a mpsc::channel or timeout. Is there a clear idiom to make this work? I've seen the unstable approach described in mpsc::Select but this Github discussion suggests it is not a robust approach. Is there a better-recommended way for me to achieve receive-or-timeout semantics?

like image 553
Bosh Avatar asked Jun 14 '16 19:06

Bosh


People also ask

When should you close a channel?

It's OK to leave a Go channel open forever and never close it. When the channel is no longer used, it will be garbage collected. Note that it is only necessary to close a channel if the receiver is looking for a close. Closing the channel is a control signal on the channel indicating that no more data follows.

What happens when you close a channel in Go?

We can close a channel in Golang with the help of the close() function. Once a channel is closed, we can't send data to it, though we can still read data from it. A closed channel denotes a case where we want to show that the work has been done on this channel, and there's no need for it to be open.

How do you Timeout a Goroutine?

Examples of How to timeout Out a Goroutine in Go: Using time. Sleep() Observe here that the time is hardcoded in to the anonymous functions (example: time. Second * 2).

What is a Goroutine?

A goroutine is a function that executes simultaneously with other goroutines in a program and are lightweight threads managed by Go. A goroutine takes about 2kB of stack space to initialize.


1 Answers

I don't know how you'd do it with the standard library channels, but the chan crate provides a chan_select! macro:

#[macro_use]
extern crate chan;

use std::time::Duration;

fn main() {
    let (_never_sends, never_receives) = chan::sync::<bool>(1);
    let timeout = chan::after(Duration::from_millis(50));

    chan_select! {
        timeout.recv() => {
            println!("timed out!");
        },
        never_receives.recv() => {
            println!("Shouldn't have a value!");
        },
    }
}
like image 170
Shepmaster Avatar answered Oct 05 '22 11:10

Shepmaster