This commit is contained in:
Kovid Goyal
2025-06-05 20:59:09 +05:30
parent a783d4932e
commit 3feea5b279
3 changed files with 34 additions and 33 deletions

View File

@@ -23,6 +23,14 @@ func (self *Context) NumberOfThreads() int {
return int(self.num_of_threads.Load())
}
func (self *Context) EffectiveNumberOfThreads() int {
ans := int(self.num_of_threads.Load())
if ans <= 0 {
ans = max(1, runtime.NumCPU())
}
return ans
}
// parallel processes the data in separate goroutines.
func (self *Context) Parallel(start, stop int, fn func(<-chan int)) {
count := stop - start
@@ -30,14 +38,7 @@ func (self *Context) Parallel(start, stop int, fn func(<-chan int)) {
return
}
procs := self.NumberOfThreads()
if procs <= 0 {
procs = runtime.NumCPU()
}
if procs > count {
procs = count
}
procs := min(self.EffectiveNumberOfThreads(), count)
c := make(chan int, count)
for i := start; i < stop; i++ {
c <- i
@@ -45,7 +46,7 @@ func (self *Context) Parallel(start, stop int, fn func(<-chan int)) {
close(c)
var wg sync.WaitGroup
for i := 0; i < procs; i++ {
for range procs {
wg.Add(1)
go func() {
defer wg.Done()