考虑一组检查工作,每个检查工作都有独立的逻辑,因此它们似乎很适合并发运行,例如:
type Work struct {
// ...
}
// This Check could be quite time-consuming
func (w *Work) Check() bool {
// return succeed or not
//...
}
func CheckAll(works []*Work) {
num := len(works)
results := make(chan bool, num)
for _, w := range works {
go func(w *Work) {
results <- w.Check()
}(w)
}
for i := 0; i < num; i++ {
if r := <-results; !r {
ReportFailed()
break;
}
}
}
func ReportFailed() {
// …Run Code Online (Sandbox Code Playgroud) 我想同时对切片的元素执行操作
我正在使用sync/errgroup包来处理并发
这是 Go Playground 上的最小复制品https://go.dev/play/p/yBCiy8UW_80
import (
"fmt"
"golang.org/x/sync/errgroup"
)
func main() {
eg := errgroup.Group{}
input := []int{0, 1, 2}
output1 := []int{}
output2 := make([]int, len(input))
for i, n := range input {
eg.Go(func() (err error) {
output1 = append(output1, n+1)
output2[i] = n + 1
return nil
})
}
eg.Wait()
fmt.Printf("with append %+v", output1)
fmt.Println()
fmt.Printf("with make %+v", output2)
}
Run Code Online (Sandbox Code Playgroud)
输出
with append [3 3 3]
with make [0 0 3]
Run Code Online (Sandbox Code Playgroud)
与预期相比[1 …
package main
import "fmt"
import "runtime"
import "time"
func check(id int) {
fmt.Println("Checked", id)
<-time.After(time.Duration(id)*time.Millisecond)
fmt.Println("Woke up", id)
}
func main() {
defer runtime.Goexit()
for i := 0; i <= 10; i++ {
fmt.Println("Called with", i)
go check(i)
}
fmt.Println("Done for")
}
Run Code Online (Sandbox Code Playgroud)
我是Go的新手,所以任何指针都会很棒.我怎么去调试这样的东西?
您可以运行代码段http://play.golang.org/p/SCr8TZXQUE
更新:这<-time.After(time.Duration(id)*time.Millisecond)在游乐场没有线路的情况下工作 ,我想知道为什么?(正如@dystroy所说,这可能是因为游乐场处理时间的方式)
当我在本地尝试时,这是输出:
Called with 0
Called with 1
Checked 0
Called with 2
Checked 1
Called with 3
Checked 2
Called with 4
Woke up 0
Checked 3
Called with 5 …Run Code Online (Sandbox Code Playgroud) 注意:"Go-lang parallel segment运行速度慢于系列段"问题涉及竞争条件,这个问题还有另外一个问题,因此它不是重复的.
我试图找到以下情况的解释:运行并行快速排序导致使用go例程完成更长的运行时间.
基准是在代码之后:
package c9sort
import (
"time"
)
var runInParllel bool
func Quicksort(nums []int, parallel bool) ([]int, int) {
started := time.Now()
ch := make(chan int)
runInParllel = parallel
go quicksort(nums, ch)
sorted := make([]int, len(nums))
i := 0
for next := range ch {
sorted[i] = next
i++
}
return sorted, int(time.Since(started).Nanoseconds() / 1000000)
}
func quicksort(nums []int, ch chan int) {
// Choose first number as pivot
pivot := nums[0]
// Prepare secondary slices
smallerThanPivot …Run Code Online (Sandbox Code Playgroud) 我想问几个服务器的数据(例如多个只读副本).在这项任务中,最重要的是速度,因此应该提供第一个结果,并且可以忽略所有其他结果.
我有绕过这些数据的惯用方法的问题.当它退出时,所有有这个问题的东西都是可以的(所有较慢的goroutine都没有完成它们的工作,因为主进程存在).但是当我们取消注释最后一行(使用Sleep)时,我们可以看到其他goroutines也正在做他们的工作.
现在我通过频道推送数据有没有办法不推动它们?
处理这类问题的好方法是什么?
package main
import (
"fmt"
"log"
"math/rand"
"time"
)
type Result int
type Conn struct {
Id int
}
func (c *Conn) DoQuery(params string) Result {
log.Println("Querying start", params, c.Id)
time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond)
log.Println("Querying end", params, c.Id)
return Result(1000 + c.Id*c.Id)
}
func Query(conns []Conn, query string) Result {
ch := make(chan Result)
for _, conn := range conns {
go func(c Conn) {
ch <- c.DoQuery(query)
}(conn)
}
return <-ch
}
func main() {
conns …Run Code Online (Sandbox Code Playgroud) 如果我http.ListenAndServe在用户点击URL时使用提供响应,我是否应该将该函数中的相应操作作为goroutine触发?
例如,说我正在听/:
func main() {
http.HandleFunc("/", provideMainContent)
}
func provideMainContent(w http.ResponseWriter, r *http.Request) {
/// Bunch of code, looks up details in databases, parses, then returns
}
Run Code Online (Sandbox Code Playgroud)
是否应该将一堆代码provideMainContent包装在一个goroutine中,这样它不会减慢事后发生的任何潜在请求?
我们可以在Go lang两次启动一个十分水平通道吗?
package main
import (
"fmt"
)
func emit(c chan string) {
words := []string {"The", "quick", "brown", "fox"}
for _, word := range words {
c <- word
}
close(c)
}
Run Code Online (Sandbox Code Playgroud)
在函数main中如果我尝试使用相同的通道两次,我将获得该通道的默认值
func main() {
wordChannel := make(chan string)
go emit(wordChannel)
for word := range wordChannel {
fmt.Printf("%s ", word)
}
go emit(wordChannel)
word1 := <-wordChannel
fmt.Printf("%s" , word1) // prints Default value
}
Run Code Online (Sandbox Code Playgroud)
所以再次使用它我要声明另一个频道.如果这不是错误,为什么在Go Lang中完成.?我正在使用go -lang 1.6版
我是Go的新手,我可能会忽略这一点,但为什么Go通道限制在缓冲通道的最大缓冲区大小可以有?例如,如果我制作一个这样的频道
channel := make(chan int, 100)
Run Code Online (Sandbox Code Playgroud)
我不能在没有阻塞的情况下向频道添加超过100个元素,这有什么原因吗?此外,它们无法动态调整大小,因为通道API不支持它.
这似乎限制了语言支持单一机制的通用同步,因为与无界信号相比,它缺乏便利性.例如,可以无限制地增加广义信号量的值.
所以我确实有一个并发的quicksort实现。看起来像这样:
func Partition(A []int, p int, r int) int {
index := MedianOf3(A, p, r)
swapArray(A, index, r)
x := A[r]
j := p - 1
i := p
for i < r {
if A[i] <= x {
j++
tmp := A[j]
A[j] = A[i]
A[i] = tmp
}
i++
}
swapArray(A, j+1, r)
return j + 1
}
func ConcurrentQuicksort(A []int, p int, r int) {
wg := sync.WaitGroup{}
if p < r {
q := Partition(A, p, …Run Code Online (Sandbox Code Playgroud) 我正在YouTube上观看有关并发模式的视频。有一个乒乓球的例子:
type Ball struct{ hits int }
func main() {
table := make(chan *Ball)
go player("ping", table)
go player("pong", table)
table <- new(Ball)
time.Sleep(1 * time.Second)
<-table
}
func player(name string, table chan *Ball) {
for {
ball := <-table
ball.hits++
fmt.Println(name, ball.hits)
time.Sleep(100 * time.Millisecond)
table <- ball
}
}
Run Code Online (Sandbox Code Playgroud)
哪个应该给出结果:
Ping 1
Pong 2
Ping 3
Pong 4
...
Run Code Online (Sandbox Code Playgroud)
但是,如果我删除一个球员的例行程序,例如“ pong”:
// go player("pong", table) // remove this line
Run Code Online (Sandbox Code Playgroud)
我只有一个结果:
Ping 1
Run Code Online (Sandbox Code Playgroud)
我不知道func播放器中有一个for循环,“ table”通道将Ball传给ball,在循环结束时,我们将Ball放回到channel表中。为什么玩家“ ping”不能自己玩?