works:programmer:go:async

Async

package main
 
import (
	"strconv"
	"time"
	"sync"
	"fmt"
)
 
var counter int = 0
var counterLock *sync.Mutex = &sync.Mutex{}
 
func dosomething(millisecs time.Duration, wg *sync.WaitGroup) {
  wg.Add(1)
  go func() {
      defer wg.Done()
      counterLock.Lock()
      counter += 1
      counterLock.Unlock()
 
      duration := millisecs * time.Millisecond
      time.Sleep(duration)
      fmt.Println("Function in background, duration:", duration)
  }()
}
 
func main() {
  var wg sync.WaitGroup
  fmt.Println("Hello, playground")
  dosomething(1600, &wg)
  dosomething(200, &wg)
  dosomething(400, &wg)
  dosomething(150, &wg)
  dosomething(600, &wg)
  wg.Wait()
  fmt.Println("Done " + strconv.Itoa(counter) + " tasks...")
}
works/programmer/go/async.txt · Last modified: 2019/09/15 22:13 by Chugreev Eugene