Created
February 2, 2021 21:29
-
-
Save yeti-detective/5bffba83e21ad9df6cc76b6c5667e165 to your computer and use it in GitHub Desktop.
Proof of Concept for using goroutine and channel to accomplish async functionality
This file contains hidden or 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
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"time" | |
) | |
func main() { | |
// create a single channel of size 1 | |
// the belief is that asyncRes will wait to populate the channel if it has data in it | |
// therefore, asyncRes will not overwrite the value of syncChan until the previous data is drained | |
syncChan := make(chan resHolder, 1) | |
for idx := 0; idx < 10; idx++ { | |
go asyncRes(idx, syncChan) | |
} | |
receivedData := make(map[int]resHolder, 10) | |
for idx2 := 0; idx2 < 10; idx2++ { | |
getData := <-syncChan | |
receivedData[idx2] = getData | |
} | |
fmt.Println("Contents of receivedData:") | |
fmt.Printf("%+v\n", receivedData) | |
} | |
type resHolder struct { | |
randNum int64 | |
ord int | |
} | |
func asyncRes(ord int, sendRes chan resHolder) { | |
// i am surprised there is no need to close the channel | |
rand.Seed(time.Now().UnixNano()) | |
randInt := rand.Int63()%1000 + 1 | |
time.Sleep(time.Duration(randInt) * time.Millisecond) | |
sendData := resHolder{randNum: randInt, ord: ord} | |
sendRes <- sendData | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment