Skip to content

Commit

Permalink
Improvement: 所有goroutine都查找完,没有找到target
Browse files Browse the repository at this point in the history
  • Loading branch information
sunyujia committed Jan 4, 2022
1 parent ab1d488 commit 94d9fc1
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/q017.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"os"
"sync"
"time"
)

Expand All @@ -15,20 +16,32 @@ func main() {
target := 345
ctx, cancel := context.WithCancel(context.Background())
resultChan := make(chan bool)
wg := &sync.WaitGroup{}
finishChan := make(chan struct{})
for i := 0; i < dataLen; i += size {
end := i + size
if end >= dataLen {
end = dataLen - 1
}
go SearchTarget(ctx, data[i:end], target, resultChan)
wg.Add(1)
go func() {
defer wg.Done()
SearchTarget(ctx, data[i:end], target, resultChan)
}()
}
go func() {
wg.Wait()
finishChan <- struct{}{}
}()
select {
case <-timer.C:
fmt.Fprintln(os.Stderr, "Timeout! Not Found")
cancel()
case <-resultChan:
fmt.Fprintf(os.Stdout, "Found it!\n")
cancel()
case <- finishChan:
fmt.Printf("[%d] not found in slice\n", target)
}

time.Sleep(time.Second * 2)
Expand Down

0 comments on commit 94d9fc1

Please sign in to comment.