goconcurrencyroutines

Swap Concurrent Function


I am trying to figure out how to make concurrent the forward Swap function in Go for learning concepts purpose:

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))
  }
}

So far I have came up with this solution:

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)
    }
}

It seems to work but I cannot be sure about it. How can I measure this and does anyone knows how to really make a simple Swap function concurrent in Go?


Solution

  • I am sorry for the question but I figured out how to solve this. It took days for me to be able to do this and on the day I posted at this forum some hours later I discovered how to solve it. I am going to post the code and the walkthrough this was given to me in a Senior Golang Job Interview and I could not answer, I hope this can help someone.

    // 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)
        }
    }
    

    I really appreciate any comments, improvements and conceptual references on this.