Created
March 31, 2020 13:02
-
-
Save foolishway/dd378d0998ae81bad6754f3ac85afc78 to your computer and use it in GitHub Desktop.
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 ( | |
"fmt" | |
"runtime" | |
"sync" | |
"time" | |
) | |
type ProductConsumer struct { | |
ch chan string | |
wg sync.WaitGroup | |
} | |
func (pc *ProductConsumer) Product() { | |
now := time.Now() | |
for c := time.Now(); c.Sub(now) < time.Duration(1 * time.Minute); { | |
c = time.Now() | |
taskTime := c.UnixNano() | |
pc.ch <- fmt.Sprintf("%d task...\n", taskTime) | |
} | |
//task producted complete then close the channel | |
fmt.Println("Product task complete.") | |
close(pc.ch) | |
} | |
func (pc *ProductConsumer) Consume() { | |
cpuNum := runtime.NumCPU() | |
pc.startN(cpuNum) | |
} | |
func (pc *ProductConsumer) startN(n int) { | |
for i := 0; i < n; i++ { | |
pc.wg.Add(1) | |
go func(n int) {pc.start(n)}(i) | |
} | |
} | |
func (pc *ProductConsumer) start(n int) { | |
defer pc.wg.Done() | |
for task := range pc.ch { | |
time.Sleep(time.Second) | |
fmt.Printf("Consume the %s", task) | |
} | |
fmt.Printf("Consumer%d is over.\n", n) | |
} | |
func main() { | |
pc := &ProductConsumer{ch: make(chan string, 100), wg: sync.WaitGroup{}} | |
go pc.Product() | |
pc.Consume() | |
defer func() { | |
pc.wg.Wait() | |
fmt.Println("Main is over.") | |
}() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment