golang 多線程尋找檔案內容

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
 1 package main 2  3 import ( 4     "fmt" 5     "io/ioutil" 6     "os" 7     "path/filepath" 8     "strings" 9 )10 11 var matchCount = 012 var ch = make(chan int, 512)13 14 func findFile(path string, text string) {15     var pathArray [100]string16     var count = 017     filepath.Walk(path, func(path string, info os.FileInfo, err error) error {18         if err != nil {19         }20         //find text21         if !info.IsDir() {22             if info.Size() < 1024*1024 {23                 pathArray[count] = path24                 count++25                 if count >= 100 {26                     count = 027                     go findText(pathArray[0:100], text)28                     <-ch29                 }30             }31         }32         return nil33     })34     go findText(pathArray[0:count], text)35     <-ch36 37     fmt.Printf("一共發現了 %d 個匹配的檔案", matchCount)38 39 }40 41 func findText(paths []string, text string) {42     for _, path := range paths {43         fi, err := os.Open(path)44         if err != nil {45             panic(err)46         }47         defer fi.Close()48         fd, err := ioutil.ReadAll(fi)49         if err != nil {50             panic(err)51         }52 53         if strings.Index(string(fd), text) > -1 {54             matchCount++55             fmt.Println(path)56         }57     }58     ch <- 159 }60 61 func main() {62     args := os.Args63     if len(args) < 3 {64         fmt.Println("需要兩個參數 path text")65         return66     }67     path := args[1]68     text := args[2]69 70     _, err := os.Stat(path)71 72     if err != nil {73         fmt.Println("path不存在")74     } else {75         findFile(path, text)76     }77 }

 計數器增加的時候應該加鎖

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.