Contents
Go 代码片段
go goroutines pool
package main
import (
"fmt"
"github.com/sourcegraph/conc/pool"
)
func main() {
p := pool.New().WithMaxGoroutines(3)
for i := 1; i <= 5; i++ {
p.Go(func() {
fmt.Println(i)
})
}
p.Wait()
}
带ctx 的go goroutines pool
package main
import (
"context"
"errors"
"fmt"
"github.com/sourcegraph/conc/pool"
)
func main() {
p := pool.New().
WithMaxGoroutines(4).
WithContext(context.Background()).
WithCancelOnError()
for i := 0; i < 3; i++ {
i := i
p.Go(func(ctx context.Context) error {
if i == 2 {
return errors.New("I will cancel all other tasks!")
}
<-ctx.Done()
return nil
})
}
err := p.Wait()
fmt.Println(err)
// Output:
// I will cancel all other tasks!
}
channel
package main
import (
"fmt"
)
func main() {
ch := make(chan int, 3)
// wg := conc.NewWaitGroup()
go func() {
for i := 0; i < 1000; i++ {
ch <- i
}
close(ch)
}()
// wg.Wait()
for v := range ch {
fmt.Println(v)
}
}
package main
import (
"fmt"
"github.com/sourcegraph/conc"
)
func main() {
ch := make(chan int)
// ch2 := make(chan bool)
wg := conc.NewWaitGroup()
wg.Go(func() {
for i := 0; i < 100; i++ {
ch <- i
}
close(ch)
})
for sub := range ch {
fmt.Println(sub)
}
}
复杂结构体slice排序
type Person struct {
Name string
Age int
Book int
}
people := []Person{
{"Alice", 30, 5},
{"Bob", 25, 2},
{"Charlie", 30, 55},
{"David", 25, 33},
}
// 使用 sort.Slice 进行排序,按年龄升序排列,年龄相同则按book排序
sort.Slice(people, func(i, j int) bool {
if people[i].Age == people[j].Age {
return people[i].Book < people[j].Book
}
return people[i].Age < people[j].Age
})