为什么此代码仅在<时有效;在结果之前<-味精;?我认为<-sem为新的子例程释放了缓冲区。除此之外,有没有更好的方法从go例程中的函数返回结果?
从逻辑上讲,我想这样做,但它不起作用,除非<-sem高于结果<-msg。
var msg = printer(account)
results<-msg;
<-sem;
这是我的代码:
package main
import (
"fmt"
"strconv"
"time"
//"runtime"
"math/rand"
)
var intSlice = []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}
func printer(account int) string {
n := rand.Intn(1)
fmt.Printf("Sleeping %d seconds...\n", n)
time.Sleep(time.Duration(n)*time.Second)
return "Account Done " + strconv.Itoa(account)
}
func main() {
threads := 2
results := make(chan string, threads)
sem := make(chan bool, threads)
for _, account := range intSlice {
sem <- true //block
go func(account int) {
var msg = printer(account)
defer func() { <-sem; results<-msg; }()
}(account)
}
for i := 0; i < cap(sem); i++ {
sem <- true
}
for i := 0; i < len(intSlice); i++ {
select {
case msg1 := <-results:
fmt.Println("received", msg1)
}
}
}
慕慕森
相关分类