1 回答
TA贡献1790条经验 获得超9个赞
根据给出的答案,我了解到存在数据竞争案例。
我用带有sync.Mutex的外部函数解决了它
package main
import (
"bufio"
"fmt"
"log"
"net/http"
"os"
"sync"
"time"
"github.com/panjf2000/ants"
)
var (
sitelist = make(map[string]int8)
)
var wg sync.WaitGroup
var m sync.Mutex
func add(address string, status int8, m *sync.Mutex) {
m.Lock()
sitelist[address] = status
m.Unlock()
}
func check(pool interface{}) {
address := pool.(string)
client := &http.Client{}
client.Timeout = time.Second * 45
req, _ := http.NewRequest("GET", "http://"+address, nil)
if response, err := client.Do(req); err == nil {
status := response.StatusCode
if status == 200 {
add(address, 1, &m)
} else {
add(address, 0, &m)
}
} else {
add(address, 0, &m)
}
}
func main() {
defer ants.Release()
p, _ := ants.NewPoolWithFunc(1000, func(i interface{}) {
check(i)
wg.Done()
})
defer p.Release()
file, err := os.Open("example.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
a := scanner.Text()
wg.Add(1)
_ = p.Invoke(string(a))
}
wg.Wait()
fmt.Println(len(sitelist))
}
- 1 回答
- 0 关注
- 77 浏览
添加回答
举报