English 中文(简体)
How do I find out if a goroutine is done, without blocking?
原标题:

All the examples I ve seen so far involve blocking to get the result (via the <-chan operator).

My current approach involves passing a pointer to a struct:

type goresult struct {
    result resultType;
    finished bool;
}

which the goroutine writes upon completion. Then it s a simple matter of checking finished whenever convenient. Do you have better alternatives?

What I m really aiming for is a Qt-style signal-slot system. I have a hunch the solution will look almost trivial (chans have lots of unexplored potential), but I m not yet familiar enough with the language to figure it out.

最佳回答

You can use the "comma, ok" pattern (see their page on "effective go"):

foo     := <- ch; // This blocks.
foo, ok := <- ch; // This returns immediately.
问题回答

Select statements allows you to check multiple channels at once, taking a random branch (of the ones where communication is waiting):

func main () {
    for {
    select {
        case w := <- workchan:
            go do_work(w)
        case <- signalchan:
            return
        // default works here if no communication is available
        default:
            // do idle work
    }
    }
}

For all the send and receive expressions in the "select" statement, the channel expressions are evaluated, along with any expressions that appear on the right hand side of send expressions, in top-to-bottom order. If any of the resulting operations can proceed, one is chosen and the corresponding communication and statements are evaluated. Otherwise, if there is a default case, that executes; if not, the statement blocks until one of the communications can complete.

You can also peek at the channel buffer to see if it contains anything by using len:

if len(channel) > 0 {
  // has data to receive
}

This won t touch the channel buffer, unlike foo, gotValue := <- ch which removes a value when gotValue == true.





相关问题
Connecting to a signal hidden by QMessageBox

I want to show the user a warning QMessageBox with a link inside. This is relatively easy, I just need to make sure I set the RichText text format on the message box and the QMessageBox setup does the ...

Qt library event loop problems

I m writing a DLL that is used as a plugin by another application and would like to leverage Qt s abilities. I have all of the classes set up, compiling and running, but no signals are being emitted. ...

Qt: Do events get processed in order?

If I had a class A, where one of its functions does: void A::func() { emit first_signal(); emit second_signal(); } Assuming that a class B has 2 slots, one connected to first_signal, and the ...

Qt widget update later but when?

I d like to know what happens exactly when I call a QWidget s update() method. Here is the documentation: http://doc.qt.digia.com/4.5/qwidget.html#update This function does not cause an ...

热门标签