【问题标题】:Swap Concurrent Function交换并发函数
【发布时间】:2021-12-13 20:23:56
【问题描述】:

我正在试图弄清楚如何在 Go 中使前向交换函数并发用于学习概念目的:

package main 

import "fmt"

func Swap(a, b int) (int, int) {
  return b, a
}

func main() {
  for i := 0; i <10; i++ {
   fmt.Println(Swap(i+1, i))
  }
}

到目前为止,我已经想出了这个解决方案:

package main

import "fmt"


// Only Send Channel
func Swap(a, b chan<- int) {
    go func() {
        for i := 0; i < 10; i++ {
            a <- i + 1
            b <- i
        }
    }()
}

func main() {

    a := make(chan int)
    b := make(chan int)

    Swap(a, b)

    for i := 0; i < 10; i++ {
        fmt.Printf("chan a received: %d | chan b received: %d\n", <-a, <-b)
    }
}

它似乎有效,但我不能确定。 我如何衡量这一点,有谁知道如何在 Go 中真正实现一个简单的 Swap 函数并发?

【问题讨论】:

    标签: go concurrency routines


    【解决方案1】:

    我很抱歉这个问题,但我想出了如何解决这个问题。 我花了几天的时间才能够做到这一点,几个小时后我在这个论坛上发帖的那天,我发现了如何解决它。 我将发布代码和在高级 Golang 工作面试中给我的演练,我无法回答,我希望这可以帮助某人。

    // Pass as a parameter a int slice of type channel
    // Send the swapped information throw the channel
    func Swap(a, b int, ch chan []int) {
        ch <- []int{b, a}
    }
    
    func main() {
        ch := make(chan []int)
    
        for i := 0; i < 100; i++ {
            // Call Worker with the created channel
            go Swap(i+1, i, ch)
        }
    
        for i := 0; i < 100; i++ {
            // Receive Channel Value
            fmt.Println(<-ch)
        }
    }
    

    我非常感谢任何关于此的 cmets、改进和概念参考。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-20
      相关资源
      最近更新 更多