美好的一天,
我正在嘗試實作作業人員執行之間的正確延遲,例如,作業人員需要完成 30 個任務并休眠 5 秒,我如何在代碼中跟蹤正好30 個任務已完成然后才睡5 秒鐘?
下面是創建一個由30 個工人組成的池的代碼,這些工人依次以無序方式一次執行 30 個任務,這是代碼:
import (
"fmt"
"math/rand"
"sync"
"time"
)
type Job struct {
id int
randomno int
}
type Result struct {
job Job
sumofdigits int
}
var jobs = make(chan Job, 10)
var results = make(chan Result, 10)
func digits(number int) int {
sum := 0
no := number
for no != 0 {
digit := no % 10
sum = digit
no /= 10
}
time.Sleep(2 * time.Second)
return sum
}
func worker(wg *sync.WaitGroup) {
for job := range jobs {
output := Result{job, digits(job.randomno)}
results <- output
}
wg.Done()
}
func createWorkerPool(noOfWorkers int) {
var wg sync.WaitGroup
for i := 0; i < noOfWorkers; i {
wg.Add(1)
go worker(&wg)
}
wg.Wait()
close(results)
}
func allocate(noOfJobs int) {
for i := 0; i < noOfJobs; i {
if i != 0 && i%30 == 0 {
fmt.Printf("SLEEPAGE 5 sec...")
time.Sleep(10 * time.Second)
}
randomno := rand.Intn(999)
job := Job{i, randomno}
jobs <- job
}
close(jobs)
}
func result(done chan bool) {
for result := range results {
fmt.Printf("Job id %d, input random no %d , sum of digits %d\n", result.job.id, result.job.randomno, result.sumofdigits)
}
done <- true
}
func main() {
startTime := time.Now()
noOfJobs := 100
go allocate(noOfJobs)
done := make(chan bool)
go result(done)
noOfWorkers := 30
createWorkerPool(noOfWorkers)
<-done
endTime := time.Now()
diff := endTime.Sub(startTime)
fmt.Println("total time taken ", diff.Seconds(), "seconds")
}
播放:https : //go.dev/play/p/lehl7hoo-kp
目前尚不清楚如何確保完成 30 個任務以及在哪里插入延遲,我將不勝感激
uj5u.com熱心網友回復:
好的,讓我們從這個作業示例開始:
func Test_t(t *testing.T) {
// just a published, this publishes result on a chan
publish := func(s int, ch chan int, wg *sync.WaitGroup) {
ch <- s // this is blocking!!!
wg.Done()
}
wg := &sync.WaitGroup{}
wg.Add(100)
// we'll use done channel to notify the work is done
res := make(chan int)
done := make(chan struct{})
// create worker that will notify that all results were published
go func() {
wg.Wait()
done <- struct{}{}
}()
// let's create a jobs that publish on our res chan
// please note all goroutines are created immediately
for i := 0; i < 100; i {
go publish(i, res, wg)
}
// lets get 30 args and then wait
var resCounter int
forloop:
for {
select {
case ss := <-res:
println(ss)
resCounter = 1
// break the loop
if resCounter%30 == 0 {
// after receiving 30 results we are blocking this thread
// no more results will be taken from the channel for 5 seconds
println("received 30 results, waiting...")
time.Sleep(5 * time.Second)
}
case <-done:
// we are done here, let's break this infinite loop
break forloop
}
}
}
我希望這能進一步說明它是如何做到的。
那么,你的代碼有什么問題?老實說,看起來還不錯(我的意思是發布了 30 個結果,然后代碼等待,然后還有 30 個結果,等等),但問題是您想在哪里等待?
我猜有幾種可能:
創建工人(這就是您的代碼現在的作業方式,正如我所見,它以 30 個包的形式發布作業;請注意,您在
digit函式中的 2 秒延遲僅適用于執行代碼的 goroutine)觸發工人(所以“等待”代碼應該在工人函式中,不允許運行更多的工人 - 所以它必須觀察發布了多少結果)
處理結果(這是我的代碼的作業方式,正確的同步在
forloop)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/385981.html
上一篇:TestMain用于所有測驗?
