【问题标题】:Concurrent Bubble sort in golanggolang中的并发冒泡排序
【发布时间】:2022-01-28 07:40:17
【问题描述】:

谁能给我解释一下 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)
}

【问题讨论】:

    标签: sorting go concurrency bubble-sort


    【解决方案1】:

    您的代码根本不起作用。 ConcurrentBubbleSortBubbleSortOdd + BubbleSortEven 将导致数据竞争。尝试使用go run -race main.go 运行您的代码。由于数据竞争,排序后数组的数据会不正确,也不会排序。

    为什么慢?我猜是因为数据竞争,导致数据竞争的 goroutine 太多。

    线程分析器检测执行期间发生的数据竞争 的多线程进程。在以下情况下会发生数据竞争:

    1. 单个进程中的两个或多个线程访问同一内存 同时定位,并且

    2. 至少有一个访问是用于写入的,并且

    3. 线程没有使用任何独占锁来控制它们的 访问该内存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-09
      • 2015-10-12
      • 2011-12-21
      • 2011-07-15
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 2015-09-12
      相关资源
      最近更新 更多