Can I get a result from one of several larynxes in Go?

I just recently learned about the Google programming language, Go. I was intrigued by the proposed concurrency support and decided to learn more about it. However, I went to see how Go implemented a specific concurrency function, and so far I have not seen any evidence that this function exists at all.

Here's a hypothetical situation: suppose we program a function to determine the Foo value for a particular input. For any given input, the value of Foo is either in domain A or in domain B (not both). The search methods in these domains are completely different, but they share the property that successful search queries tend to return quickly, while an unsuccessful search must go through the entire data set in order to be exhaustive and therefore take a lot of time.

Now in other languages ​​where concurrency is used (for example, Cilk ), you can program the Foosearch function so that it spawns the Asearch function and the Bsearch function. These functions will be executed simultaneously, and whenever any of them comes with an answer, this answer will be passed to the calling Foosearch function, which will terminate any functions that it generated that did not return.

With Go goroutines, however, it seems that you can only connect two procedures with a channel, so you cannot configure a channel to which either Asearch or Bsearch can be sent, depending on what basis the answer was found, and From read it by Foosearch. It also looks like you cannot read from the channel without blocking it - so you could not Foosearch start Asearch and Bsearch and configure the channels from both, and then run in the check loop to make sure that one or the other answer.

Do I understand the limits of Go concurrency? Is there any other way to achieve this result?

+3
source share
2 answers

No, I do not believe that your understanding of the limits of Go is correct.

-, Go, . Asearch, Bsearch, .

, , select. Go tutorial, , , , :

21    func server(op binOp, service chan *request, quit chan bool) {
22        for {
23            select {
24            case req := <-service:
25                go run(op, req);  // don't wait for it
26            case <-quit:
27                return;
28            }
29        }
30    }

, .

x, ok = <-ch
x, ok := <-ch
var x, ok = <-ch

. continue, ok true , ; ok false x (Β§ ).

, goroutines . , , select, , , , , - ,.

+16

select .

, .

var c1, c2 chan int;
var result int;

select {
case result = <-c1:
    print("received ", result, " from c1\n");
case result = <-c2:
    print("received ", result, " from c2\n");
}

+5

Source: https://habr.com/ru/post/1722920/


All Articles