登录
首页 >  Golang >  Go问答

使用Golang实现的并发冒泡排序

来源:stackoverflow

时间:2024-03-05 23:15:24 460浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《使用Golang实现的并发冒泡排序》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

有人可以向我解释一下下面代码中的 goroutine 是如何工作的吗,顺便说一句,我写的。

当我执行 bubblesortvanilla 时,大小为 100000 的列表大约需要 15 秒 当我使用奇偶阶段执行 bubblesortodd 和 bubblesorteven 时,大约需要 7 秒。但当我只进行 concurrentbubblesort 时,只需要大约 1.4 秒。

无法真正理解为什么单个 concurrentbubblesort 更好? 这是创建两个线程及其处理的开销的原因吗 与列表长度相同或一半?

我尝试分析代码,但不太确定如何查看正在创建的线程数或每个线程的内存使用情况等

package main

import (
    "fmt"
    "math/rand"
    "sync"
    "time"
)

func BubbleSortVanilla(intList []int) {
    for i := 0; i < len(intList)-1; i += 1 {
        if intList[i] > intList[i+1] {
            intList[i], intList[i+1] = intList[i+1], intList[i]
        }
    }
}

func BubbleSortOdd(intList []int, wg *sync.WaitGroup, c chan []int) {
    for i := 1; i < len(intList)-2; i += 2 {
        if intList[i] > intList[i+1] {
            intList[i], intList[i+1] = intList[i+1], intList[i]
        }
    }
    wg.Done()
}

func BubbleSortEven(intList []int, wg *sync.WaitGroup, c chan []int) {
    for i := 0; i < len(intList)-1; i += 2 {
        if intList[i] > intList[i+1] {
            intList[i], intList[i+1] = intList[i+1], intList[i]
        }
    }
    wg.Done()
}

func ConcurrentBubbleSort(intList []int, wg *sync.WaitGroup, c chan []int) {
    for i := 0; i < len(intList)-1; i += 1 {
        if intList[i] > intList[i+1] {
            intList[i], intList[i+1] = intList[i+1], intList[i]
        }
    }
    wg.Done()
}

func main() {
    // defer profile.Start(profile.MemProfile).Stop()
    rand.Seed(time.Now().Unix())
    intList := rand.Perm(100000)
    fmt.Println("Read a sequence of", len(intList), "elements")

    c := make(chan []int, len(intList))
    var wg sync.WaitGroup

    start := time.Now()
    for j := 0; j < len(intList)-1; j++ {
        // BubbleSortVanilla(intList) // takes roughly 15s

        // wg.Add(2)
        // go BubbleSortOdd(intList, &wg, c)  // takes roughly 7s
        // go BubbleSortEven(intList, &wg, c)

        wg.Add(1)
        go ConcurrentBubbleSort(intList, &wg, c) // takes roughly 1.4s
    }
    wg.Wait()
    elapsed := time.Since(start)

    // Print the sorted integers
    fmt.Println("Sorted List: ", len(intList), "in", elapsed)
}

正确答案


您的代码根本无法运行。 ConcurrentBubbleSortBubbleSortOdd + BubbleSortEven 将导致数据争用。尝试使用 go run -race main.go 运行您的代码。由于数据竞争,数组的数据在排序后会出现错误,而且也没有排序。

为什么这么慢?我猜是因为数据竞争,并且有太多的 go 例程导致了数据竞争。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《使用Golang实现的并发冒泡排序》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>