Last active
November 14, 2019 07:42
-
-
Save didasy/77e66e85ef465560df20f7eaf7cdc1b5 to your computer and use it in GitHub Desktop.
Example of Concurrent Processing With Channels
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
package main | |
import ( | |
"context" | |
"flag" | |
"fmt" | |
"runtime" | |
ipgen "github.com/wahyuhadi/go-ipgen" | |
) | |
var ( | |
workerCount = flag.Int("wk", runtime.NumCPU(), "Worker count") | |
subnet = flag.String("subnet", "192.168.1.1/24", "Subnet Network") | |
) | |
func main() { | |
flag.Parse() | |
ip := ipgen.IpAddressGen(*subnet) | |
ctx, cancel := context.WithCancel(context.Background()) | |
defer cancel() | |
doneChan := make(chan bool, *workerCount) | |
retChan := make(chan string, *workerCount) | |
for i := 0; i < *workerCount; i++ { | |
go work(ctx, retChan, doneChan) | |
} | |
go func() { | |
for _, i := range ip { | |
retChan <- i | |
} | |
}() | |
for i := 0; i < len(ip); i++ { | |
<-doneChan | |
} | |
} | |
func work(ctx context.Context, retChan <-chan string, doneChan chan<- bool) { | |
for { | |
select { | |
case <-ctx.Done(): | |
return | |
case ip := <-retChan: | |
fmt.Println(ip) | |
doneChan <- true | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment