Last active
February 18, 2024 01:52
-
-
Save elimisteve/4442820 to your computer and use it in GitHub Desktop.
Programming Challenge: Launch 4 threads, goroutines, coroutines, or whatever your language uses for concurrency, in addition to the main thread. In the first 3, add numbers together (see sample code below) and pass the results to the 4th thread. That 4th thread should receive the 3 results, add the numbers together, format the results as a strin…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Steve Phillips / elimisteve | |
// 2013.01.03 | |
// Programming Challenge: Launch 4 threads, goroutines, coroutines, or whatever your language uses for concurrency, | |
// in addition to the main thread. In the first 3, add numbers together (see sample code below) and pass the results | |
// to the 4th thread. That 4th thread should receive the 3 results, add the numbers together, format the results as | |
// a string (see sample code), and pass the result back to `main` to be printed. | |
// | |
// Do this as succinctly and readably as possible. _Go!_ #golang #programming #concurrency #challenge | |
package main | |
import "fmt" | |
// intDoubler doubles the given int, then sends it through the given channel | |
func intDoubler(ch chan int, n int) { | |
ch <- n*2 | |
} | |
func main() { | |
// Make channel of ints | |
ch := make(chan int) | |
answer := make(chan string) | |
// Spawn 3 goroutines (basically threads) to process data in background | |
go intDoubler(ch, 10) | |
go intDoubler(ch, 20) | |
go func(a, b int) { ch <- a+b }(30, 40) // Take 2 ints, write sum to `ch` | |
// Create anonymous function on the fly, launch as goroutine! | |
go func() { | |
// Save the 3 values passed through the channel as x, y, and z | |
x, y, z := <-ch, <-ch, <-ch | |
// Calculate answer, write to `answer` channel | |
answer <- fmt.Sprintf("%d + %d + %d = %d", x, y, z, x+y+z) | |
}() | |
// Print answer resulting from channel read | |
fmt.Printf("%s\n", <-answer) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Would be interesting to see this done with http://libmill.org/ !