我只是尝试了下面的代码,但结果似乎有点奇怪.它首先打印奇数,然后打偶数.我真的很困惑.我原本希望它输出奇数和偶数一个接一个,就像1,2,3,4 ...... 谁能帮我?
package main
import (
"fmt"
"time"
)
func main() {
go sheep(1)
go sheep(2)
time.Sleep(100000)
}
func sheep(i int) {
for ; ; i += 2 {
fmt.Println(i,"sheeps")
}
}
Run Code Online (Sandbox Code Playgroud) 我有一个列表,其中包含一个弹出元素的函数,以及另一个"接收"弹出元素的函数.我认为接收器关闭后会关闭通道,但似乎该程序在到达之前已经死锁.这是最好的方法吗?我应该有另一个通道来检测弹出窗口何时完成?
func pop(list *[]int, c chan int) {
if len(*list) != 0 {
result := (*list)[0]
*list = (*list)[1:]
fmt.Println("about to send ", result)
c <- result
} else {
return
}
}
func receiver(c chan int) {
result := <-c
fmt.Println("received ", result)
}
var list = []int{1, 2, 3}
func main() {
fmt.Println("Main")
c := make(chan int)
go pop(&list, c)
go pop(&list, c)
for len(list) > 0 {
receiver(c)
}
close(c) //Dosen't seem to have any effect …Run Code Online (Sandbox Code Playgroud) 我想对一个函数进行基准测试:test()使用不同数量的线程来处理它.
var t1 = time.Now()
test()
var elapsed1 = time.Since(t1)
Run Code Online (Sandbox Code Playgroud)
1 ns /操作
runtime.GOMAXPROCS(1)
var t1 = time.Now()
go test()
var elapsed1 = time.Since(t1)
Run Code Online (Sandbox Code Playgroud)
1.10 ^ -6 ns /操作
func test() {
for i := 0; i < 1000000000; i++ {
float_result = f1 + f2
float_result = f1 - f2
float_result = f1 * f2
float_result = f1 / f2
float_result = f1 + f2
float_result = f1 - f2
float_result = f1 * …Run Code Online (Sandbox Code Playgroud) 如果我正确理解goroutine在系统线程之上的工作方式-它们从队列中一个接一个地运行。但这是否意味着每个goroutine都会将其上下文加载/卸载到CPU?如果是,系统线程和goroutines之间有什么区别?
最重要的问题是上下文切换的时间成本。这是对的吗?
检测哪种goroutine请求哪些数据的基础是什么?例如:我正在从goroutine A向DB发送请求,并且不等待响应,并且同时切换到下一个goroutine。系统如何理解请求来自A而不是来自B或C?
我编写了这个函数来为我的测试用例生成随机唯一id:
func uuid(t *testing.T) string {
uidCounterLock.Lock()
defer uidCounterLock.Unlock()
uidCounter++
//return "[" + t.Name() + "|" + strconv.FormatInt(uidCounter, 10) + "]"
return "[" + t.Name() + "|" + string(uidCounter) + "]"
}
var uidCounter int64 = 1
var uidCounterLock sync.Mutex
Run Code Online (Sandbox Code Playgroud)
为了测试它,我产生在不同的够程一堆从它的值,将其发送到主线程,这使结果在map[string]int做map[v] = map[v] + 1.没有对此映射的并发访问权限,它对主线程是私有的.
var seen = make(map[string]int)
for v := range ch {
seen[v] = seen[v] + 1
if count := seen[v]; count > 1 {
fmt.Printf("Generated the same uuid %d times: %#v\n", count, …Run Code Online (Sandbox Code Playgroud) 我觉得我的问题的答案是肯定的,但要求确定,因为我只是开始玩Go几天.我们是否应该将IO绑定任务(如http请求)封装到goroutine中,即使它是在顺序用例中使用的?
这是我天真的例子.假设我有一个方法可以生成3个http请求但需要按顺序执行.将invoke方法创建为goroutines 有什么好处吗?我理解下面的例子实际上会受到性能影响.
func myMethod() {
chan1 := make(chan int)
chan2 := make(chan int)
chan3 := make(chan int)
go invoke1(chan1)
res1 := <-chan1
invoke2(res1, chan2)
res2 := <-chan2
invoke3(res2, chan3)
// Do something with <-chan3
}
Run Code Online (Sandbox Code Playgroud)
我想到的一个可能的原因是,未来证明了invoke当其他开发项目开始重新使用该方法时,何时在并发上下文中调用它们的方法.还有其他原因吗?
我想要一堆goroutines来从很多服务器上获取一些信息.我正在简化下面的代码,因此它更具可读性.它看起来工作得很好,但是在完成所有任务之后就会感到恐慌,因为我从不关闭频道.问题是我不确定在哪里关闭它.
我需要你的帮助:
func main() {
ch := make(chan string)
for i:= 0; i < 10 ; i++ {
go func(c chan <- string,t int){
time.Sleep( time.Duration(rand.Intn(3000)) * time.Millisecond )
c <- strconv.Itoa(t) + " : Done " + strconv.Itoa(rand.Intn(3000))
}(ch,i)
}
for val := range ch {
fmt.Println(val)
}
}
Run Code Online (Sandbox Code Playgroud)
$ go run test_channels.go
0 : Done 1694
6 : Done 511
3 : Done 162
2 : Done 89
8 : …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个命令行测验,在该测验中,用户将被问到另一个问题,直到他们完成最后一个问题或超时为止。
我想使用频道,以便我可以学习如何正确使用它们,而且可以说,我遇到了障碍。
这个想法是将correctAnswersCh从0开始,在每个正确答案之后,它将递增1。
在将零放入通道后,测验总是在quiz()函数的第3行停止。
我在下面添加了一些代码,但是完整的代码在这里:https : //play.golang.org/p/vzRCTc7MpIK
func main() {
questions, err := getCsvData()
var limit = time.Duration(3)
flag.Parse()
if err != nil {
log.Fatal(err)
}
quizComplete := make(chan bool)
correctAnswersCh := make(chan int)
go quiz(quizComplete, questions, correctAnswersCh)
select {
case <-time.After(limit*time.Second):
fmt.Println("Timed Out")
}
fmt.Printf("Correct Answers: %v\n", <-correctAnswersCh)
}
func quiz(quizComplete chan bool, questions [][]string, correctAnswersCh chan int) {
reader := bufio.NewReader(os.Stdin)
correctAnswersCh <- 0
// execution stops here. 0 is added to correctAnswersCh, then the quiz func …Run Code Online (Sandbox Code Playgroud) 我正在使用goroutine和通道编写一些golang并发代码,这是我的代码:
package main
import "fmt"
func main() {
in := make(chan int)
go func() {
fmt.Println("Adding num to channel")
in <- 1
fmt.Println("Done")
}()
val := <- in
fmt.Println(val)
}
Run Code Online (Sandbox Code Playgroud)
我认为我创建了一个无缓冲的通道,内部通道必须等待,直到外部通道读取它为止,并且输出可能像这样:
Adding num to channel
1
Done
Run Code Online (Sandbox Code Playgroud)
但实际上,输出为:
Adding num to channel
Done
1
Run Code Online (Sandbox Code Playgroud)
我很困惑,为什么内部无缓冲通道只是在不等待读取的情况下运行
最近,我学会了-race检查go中比赛条件是否存在的选项。完整的命令是go run -race xxx.go它确实对我有很大帮助。但是和下面的代码一样,我认为检查结果是错误的,并尝试了很多方法(我在下面尝试引起恐慌)导致真正的恐慌但失败了。所以,我想知道是否该代码是正确的,比赛检查是错了吗?或者你可以修改我的代码,这样我可以查阅一个真正的恐慌。非常感谢。
package main
import "fmt"
type myType struct {
A int
}
func main(){
c:=make(chan bool)
x := new(myType)
go func(){
x = new(myType) // write to x
c <- true
}()
_ = *x // read from x
<-c
fmt.Println("end")
}
Run Code Online (Sandbox Code Playgroud)
go run -race test.go
==================
WARNING: DATA RACE
Write at 0x00c00009c010 by goroutine 6:
main.main.func1()
/Users/yaodongen/test.go:12 +0x56
Previous read at …Run Code Online (Sandbox Code Playgroud) go ×10
goroutine ×10
concurrency ×4
channel ×2
benchmarking ×1
coroutine ×1
dictionary ×1
hash ×1
pointers ×1