package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("Concurrency test")
concurrency := 5
workers := make(chan bool, concurrency)
// Ensure each worker is set to true (ready)
for i := 0; i < cap(workers); i++ {
select {
default:
workers <- true
}
}
// i is purely for output reasons
for i := 0; ; i++ {
select {
case <-workers:
output := make(chan string)
go func(w chan bool) {
defer func() {
w <- true
}()
output <- fmt.Sprintf("request %d", i)
time.Sleep(1000 * time.Millisecond)
}(workers)
fmt.Println(<-output)
}
}
}
golang 去并发模式:只让一个线程做关键事情,其他线程等待并通过工作。
package main
import (
"log"
"sync"
"time"
)
var flag bool
var wg sync.WaitGroup
func One() {
if flag {
wg.Wait()
} else {
flag = true
wg.Add(1)
log.Println("I am doing!")
// do some thing only one can do at one time
time.Sleep(5 * time.Second)
log.Println("DONE!!")
wg.Done()
// let others come in the nearest time period pass this action
go func() {
// as long as req timeout
time.Sleep(5 * time.Second)
flag = false
log.Println("next period")
}()
}
log.Println("op!")
}
func main() {
flag = false
for i := 0; i < 10; i++ {
time.Sleep(1 * time.Second)
go One()
}
time.Sleep(2 * time.Second)
log.Println("try again!")
for i := 0; i < 10; i++ {
time.Sleep(1 * time.Second)
go One()
}
time.Sleep(2 * time.Second)
log.Println("main end!")
}