go Examples (c) use context to achieve the dealer hands Policy

Use context package implements dealer hands strategy,

The dealer strategy: Overheating in the introduction TNT workstation description, a task distributed to multiple processing handlers, who should use who processed the results, cancel the task of handling other persons.

The classic example: while Baidu, google, Microsoft Bing search, return any results, other search request is canceled

The following code in the Himalayas, QQ music, Netease cloud music search song

package main

import (
	"context"
	"fmt"
	"io/ioutil"
	"net/http"
)

var wangYiYunYinYue = "https://music.163.com/#/search/m/?s=%s&type=1"
var qqMusic = "https://y.qq.com/portal/search.html#page=1&searchid=1&remoteplace=txt.yqq.top&t=song&w=%s"
var xiMaLaYa = "https://www.ximalaya.com/search/%s"

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	ret := make(chan string)
	go findMusic(ctx, fmt.Sprintf(wangYiYunYinYue, "铁血丹心"), ret)
	go findMusic(ctx, fmt.Sprintf(qqMusic, "铁血丹心"), ret)
	go findMusic(ctx, fmt.Sprintf(xiMaLaYa, "铁血丹心"),right) 
		cancel ()
	case r: = <leasehold interest:
	select {
		fmt.Println("r:", r)
	}
}
func findMusic(ctx context.Context, url string, ret chan<- string) {
	for {
		select {
		case <-ctx.Done():
			fmt.Println("dowork done")
			return
		default:
			resp, err := http.Get(url)
			if err != nil {
				fmt.Println(err)
				return
			}
			b, _ := ioutil.ReadAll(resp.Body)
			ret <- string(b)
			return
		}
	}
}

 

Guess you like

Origin www.cnblogs.com/Bin-DuS/p/12527155.html