multithreading - 为什么我的 goroutines 在完成时互相等待而不是完成?

标签 multithreading concurrency go bubble-sort goroutine

我是 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 不应该先完成吗,因为他的 slice 是最小的? 似乎所有线程都在等待其他线程完成,因为“完成”消息同时出现,无论 slice 有多大..

我的脑残在哪里? =)

提前致谢。

*编辑: 将“time.Sleep(1)”放入 bubblesort func 的 for 循环中时。它似乎工作..但我想用这段代码记录不同机器上的持续时间(我知道,我必须改变随机的东西),所以 sleep 会伪造结果。

最佳答案

事实上,对于 goroutine 的执行顺序没有任何保证。

但是,如果您通过明确让 2 个处理器内核运行来强制执行真正的并行处理:

import (
    "fmt"
    "time" //for time functions e.g. Now()
    "math/rand" //for pseudo random numbers
    "runtime"
)
...

func main() {
   runtime.GOMAXPROCS(2)

   rand.Seed( time.Now().UTC().UnixNano()) //set seed for rand.
...

然后你会得到预期的结果:

Slices filled ...
Main working ...
Thread 2 done
Thread 3 done
Thread 1 done

最好的问候

关于multithreading - 为什么我的 goroutines 在完成时互相等待而不是完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14399378/

相关文章:

Oracle - SELECT-INSERT 锁定模式

go - 为什么我会遇到此 Golang 代码的死锁?

go - 将数组或 slice 传递给 golang 中的变量 args 函数

multithreading - 如何在不使用join的情况下向python中的主线程发送信号?

multithreading - Clojure 多线程输出流

Java - 在哪里检测和捕获 SocketException

javascript - 如何在 Node.js 中使用传入的函数初始化子进程

go - 使用 Go 应用程序将生成的文件推送到 github

python - 没有名为 'Queue' 的模块

java - 如何在收到输入后通知所有线程