go语言学习笔记——常见任务的处理

138 阅读1分钟

我们在开发过程中,经常会并发处理一些任务,常见的场景主要是:

  • 并发处理多个任务,如果任意一个任务返回结果,终止;
  • 并发处理多个任务,所有任务返回结果,终止

并发处理多个任务,如果任意一个任务返回结果

比如我们需要并发调用百度、谷歌或bing查询一些检索结果,那么如果任意一个搜索引擎返回了结果,就输出给用户信息

package Class31

import (
   "fmt"
   "testing"
   "time"
)

// 假设这里是调用搜索引擎
func runTask(id int) string {
   time.Sleep(time.Millisecond * 10)
   return fmt.Sprintf("The result is from %d", id)
}

func firstResponse() string {
   numberOfRes := 10
   ch := make(chan string, numberOfRes)
   for i := 0; i < numberOfRes; i++ {
      go func(n int) {
         ret := runTask(n)
         ch <- ret
      }(i)
   }
   return <-ch
}

func TestForResponse(t *testing.T) {
   t.Log(firstResponse())
}

输出结果:

=== RUN   TestForResponse
    concurrent_test.go:28: The result is from 2
--- PASS: TestForResponse (0.01s)
PASS

输出结果会随机返回具体的数字

并发处理多个任务,所有任务返回结果

package Class32

import (
   "fmt"
   "sync"
   "testing"
   "time"
)

func runTask(id int) string {
   time.Sleep(time.Millisecond * 10)
   return fmt.Sprintf("The result is from %d", id)
}

func TestForResponse(t *testing.T) {
   var wg sync.WaitGroup
   list := make([]string, 10)
   for i := 0; i < 10; i++ {
      wg.Add(1)
      go func(n int) {
         ret := runTask(n)
         list = append(list, ret)
         wg.Done()
      }(i)
   }
   wg.Wait()
   fmt.Println(list)
}

输出结果:

=== RUN   TestForResponse
[          The result is from 7 The result is from 4 The result is from 9 The result is from 1 The result is from 2 The result is from 5 The result is from 8 The result is from 6 The result is from 0]
--- PASS: TestForResponse (0.01s)
PASS