Skip to content

Instantly share code, notes, and snippets.

@AmirMahdyJebreily
Created September 30, 2024 16:26
Show Gist options
  • Save AmirMahdyJebreily/588980569b55ffa8e2f717b1de3c94a9 to your computer and use it in GitHub Desktop.
Save AmirMahdyJebreily/588980569b55ffa8e2f717b1de3c94a9 to your computer and use it in GitHub Desktop.
An sum/sub program using Golang concurrency
package main
import "fmt"
func sum(inputs <-chan int, outputs chan<- int, num int) {
for input := range inputs {
num += input
outputs <- num // something like function return in non-goroutine functions
}
}
func main() {
inputs := make(chan int, 1) // inputs channel for sum goroutine
returns := make(chan int, 1) // outputs channel of sum goroutine
go sum(inputs, returns, 0)
var in int // for get input from user
var sumStr string // sequence of numbers added together
var out int // for get the results from goroutine
fmt.Printf("\u001B[H\u001B[2JEnter a number: ")
for fmt.Scan(&in); in != 0; fmt.Scan(&in) {
inputs <- in
out = <-returns // something like function call in non-goroutine functions
sumStr += fmt.Sprintf("%v \u001b[38;5;242m+\u001b[0m ", in)
fmt.Printf("\u001B[H\u001B[2J\u001B[34m%v\u001B[0m = %v", out, sumStr)
}
defer close(inputs)
defer close(returns)
defer fmt.Printf("The result is: \u001B[34m%v\u001B[0m", out)
}
Enter a number: 6
6 = 6 + 50
56 = 6 + 50 + 200
256 = 6 + 50 + 200 + 0
The result is: 256
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment