On Friday, 15 April 2022 at 08:31:17 UTC+1 yan.z...@gmail.com wrote:

> Thanks for your demonstration, Brian.
> Actually my code involving cgo is quite like your first case, like this 
> code:
>
> *log("start testing")*
> *go func{*
> *  for*
> *      select*
> *      case a: <=receiving*
> *      case <- killsig*
> *...*
> *}()*
>
> *subscribequotations*
> *( meanwhile the cgo of the dll will call back go functions to fill 
> receiving channel)*
> *time.Sleep(3 * time.Seconds)*
>
> *disconnect and log*
> *killsig <- true*
>

That code is obviously incomplete, but I'm guessing when you receive a 
value on killsig you return from the function.

A better Go idiom for that is to close a channel.  All the receivers on 
that channel will see that the channel is closed:

    case msg, ok <- killsig:
        // msg is the zero value and ok is false if the channel is closed

The same channel can be shared between many receivers, so it becomes a way 
of broadcasting a kill message.  See https://go.dev/tour/concurrency/4

You should never *send* on a closed channel though - that will cause a 
panic.

 

>
> I am really curious about your example on select -  is it a try... except 
> alternative?
>

It's not really anything like "try... except".

The "select" statement is specifically for channel communication.  See the 
description in the Go Tour starting here:
https://go.dev/tour/concurrency/5  # pages 5 and 6
It picks one branch where a channel is ready to send or receive, or the 
"default" branch if none are.

If you have a series of general conditions that you want to try one by one, 
then there is the "switch" statement:
https://go.dev/tour/flowcontrol/9   # pages 9 to 11

In most languages "try... except" is an error recovery mechanism which can 
handle unwinding the stack (returning from multiple levels of nested 
function calls).  The nearest equivalent to that in go is panic/recover, 
but that should only be used in very special circumstances.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/452795b8-4817-4161-84e7-02665e24ae06n%40googlegroups.com.

Reply via email to