golang多协程并发工作
package main
import (
"fmt"
"log"
"os"
"sync"
"time"
)
type Task struct {
Name string
Age int
}
func work(wg *sync.WaitGroup, jobs chan Task, w int, logger *log.Logger) {
defer wg.Done()
for true {
job, ok := <-jobs
if !ok {
break
}
logger.Printf("[%d]name=%s age=%d
", w, job.Name, job.Age)
}
}
func main() {
start := time.Now()
file, err := os.OpenFile("info.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
defer file.Close()
gLogger := log.New(file, "", log.Ldate|log.Ltime|log.Lshortfile)
gLogger.Println("[main] ready go")
wg := &sync.WaitGroup{}
jobs := make(chan Task)
workers := 10
for w := 0; w < workers; w++ {
wg.Add(1)
go work(wg, jobs, w, gLogger)
}
for i := 0; i < 10000; i++ {
task := Task{
Name: fmt.Sprintf("Name-%d", i),
Age: i,
}
jobs <- task
}
close(jobs)
wg.Wait()
gLogger.Printf("[main] done, cost: %s", time.Now().Sub(start))
}