Created
May 26, 2021 09:51
-
-
Save XUJiahua/2b54259aaef399ac7ea09d55bf000e03 to your computer and use it in GitHub Desktop.
use channel as callback
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" | |
"time" | |
) | |
// oneshot_channel make sender/receiver | |
func oneshot_channel() (chan<- int, <-chan int) { | |
ch := make(chan int) | |
return ch, ch | |
} | |
type MPSCStruct struct { | |
sender chan<- int | |
value int | |
} | |
// mpsc_channel make sender/receiver | |
func mpsc_channel(size int) (chan<- MPSCStruct, <-chan MPSCStruct) { | |
ch := make(chan MPSCStruct, size) | |
return ch, ch | |
} | |
func doMath(receiver <-chan MPSCStruct) { | |
for s := range receiver { | |
newValue := s.value + 1 | |
s.sender <- newValue | |
} | |
fmt.Println("doMath done") | |
} | |
func client(mathSender chan<- MPSCStruct, value int) int { | |
sender, receiver := oneshot_channel() | |
mathSender <- MPSCStruct{ | |
sender: sender, | |
value: value, | |
} | |
return <-receiver | |
} | |
func main() { | |
sender, receiver := mpsc_channel(2) | |
go doMath(receiver) | |
for i := 0; i < 10; i++ { | |
go func(value int) { | |
newValue := client(sender, value) | |
fmt.Printf("%d -> %d\n", value, newValue) | |
}(i) | |
} | |
time.Sleep(time.Second) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment