【发布时间】:2013-01-02 04:33:56
【问题描述】:
我对 Go 很陌生,我的代码中有一件事我不明白。 我写了一个简单的冒泡排序算法(我知道它不是很有效;))。 现在我想启动 3 个 GoRoutines。每个线程都应该独立于其他线程对他的数组进行排序。完成后,函数。应该打印一个“完成”的消息。
这是我的代码:
package main
import (
"fmt"
"time" //for time functions e.g. Now()
"math/rand" //for pseudo random numbers
)
/* Simple bubblesort algorithm*/
func bubblesort(str string, a []int) []int {
for n:=len(a); n>1; n-- {
for i:=0; i<n-1; i++ {
if a[i] > a[i+1] {
a[i], a[i+1] = a[i+1], a[i] //swap
}
}
}
fmt.Println(str+" done") //done message
return a
}
/*fill slice with pseudo numbers*/
func random_fill(a []int) []int {
for i:=0; i<len(a); i++ {
a[i] = rand.Int()
}
return a
}
func main() {
rand.Seed( time.Now().UTC().UnixNano()) //set seed for rand.
a1 := make([]int, 34589) //create slice
a2 := make([]int, 42) //create slice
a3 := make([]int, 9999) //create slice
a1 = random_fill(a1) //fill slice
a2 = random_fill(a2) //fill slice
a3 = random_fill(a3) //fill slice
fmt.Println("Slices filled ...")
go bubblesort("Thread 1", a1) //1. Routine Start
go bubblesort("Thread 2", a2) //2. Routine Start
go bubblesort("Thread 3", a3) //3. Routine Start
fmt.Println("Main working ...")
time.Sleep(1*60*1e9) //Wait 1 minute for the "done" messages
}
这是我得到的:
Slices filled ...
Main working ...
Thread 1 done
Thread 2 done
Thread 3 done
线程 2 不应该先完成,因为他的切片是最小的吗? 似乎所有线程都在等待其他线程完成,因为“完成”消息同时出现,无论切片有多大..
我的脑虫在哪里? =)
提前致谢。
*编辑: 将“time.Sleep(1)”放入bubblesort func的for循环中时。它似乎工作..但我想用这段代码记录不同机器上的持续时间(我知道,我必须改变随机的东西),所以 sleep 会伪造结果。
【问题讨论】:
-
由于您是 Go 新手,我建议您使用通道来管理同步:阅读 golang.org/doc/effective_go.html#concurrency。这是 Go 的一个非常简洁的核心功能,通常可以让你避免使用主动等待或 time.Sleep()。
-
还要注意
rand有一个互斥锁,这会损害你的并发性能;见stackoverflow.com/questions/14298523/… -
也谢谢,我修好了
-
关于 Go 的后续版本如何处理此问题的有趣历史记录 youtu.be/1I1WmeSjRSw?t=93
标签: multithreading concurrency go bubble-sort goroutine