Skip to content

Instantly share code, notes, and snippets.

@trim21
Last active July 19, 2022 05:19
Show Gist options
  • Save trim21/157f85d710dae45e29d7c10504a4c93d to your computer and use it in GitHub Desktop.
Save trim21/157f85d710dae45e29d7c10504a4c93d to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
result := MultiJudge(4, []JudgeFunc{
func(a any) bool {
fmt.Println("judge 1 called")
return a.(int) == 1
},
func(a any) bool {
fmt.Println("judge 2 called")
return a.(int) == 2
},
func(a any) bool {
fmt.Println("judge 3 called")
return a.(int) == 3
},
func(a any) bool {
fmt.Println("judge 4 called")
return a.(int) == 4
},
})
fmt.Println("multiJudge result", result)
}
type JudgeFunc func(any) bool
func MultiJudge(value any, judgeFuncs []JudgeFunc) bool {
var result int32
wg := sync.WaitGroup{}
for _, judgeFunc := range judgeFuncs {
wg.Add(1)
judgeFunc := judgeFunc
go func() {
defer wg.Done()
if atomic.LoadInt32(&result) == 0 {
if judgeFunc(value) {
atomic.StoreInt32(&result, 1)
}
}
}()
}
wg.Wait()
return result != 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment