Last active
September 21, 2015 21:56
-
-
Save simonswine/aac0574ab6473e3b052f to your computer and use it in GitHub Desktop.
Go concurrency long and short task
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 ( | |
log "github.com/Sirupsen/logrus" | |
"sync" | |
"time" | |
) | |
// work short is done right away | |
func workShort(id string) { | |
log.Infof("[%s] start short work", id) | |
time.Sleep(500 * time.Millisecond) | |
log.Infof("[%s] stop short work", id) | |
} | |
// work long is only once done globaly | |
func workLong(id string) { | |
log.Infof("[%s] start long work", id) | |
time.Sleep(5 * time.Second) | |
log.Infof("[%s] stop long work", id) | |
} | |
func work(wg *sync.WaitGroup, semLong chan bool, id string) { | |
wg.Add(1) | |
go func() { | |
// make sure decrement after leaving this coroutine | |
defer wg.Done() | |
log.Infof("[%s] start over all work", id) | |
workShort(id) | |
semLong <- true | |
workLong(id) | |
<-semLong | |
log.Infof("[%s] finish over all work", id) | |
}() | |
} | |
func main() { | |
wg := sync.WaitGroup{} | |
maxLong := 2 | |
semLong := make(chan bool, maxLong) | |
work(&wg, semLong, "A") | |
time.Sleep(1 * time.Second) | |
work(&wg, semLong, "B") | |
time.Sleep(2 * time.Second) | |
work(&wg, semLong, "C") | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment