golang使用chan

前端之家收集整理的这篇文章主要介绍了golang使用chan前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package main

//创建处理的携程
import (
    "fmt"
    "io/IoUtil"
    "os"
    "strings"
)

type FindList struct {
    ListData []string
    Readstr  chan string
    FindName string
}

func NewFindList(count int) *FindList {
    alist := make([]string,count)
    readstr := make(chan string)
    return &FindList{ListData: alist,Readstr: readstr,FindName: "go"}
}

func (mf *FindList) checkFindRet(path string) bool {
    return strings.Contains(path,mf.FindName)
}

func (mf *FindList) GetRet(list []string,aChan chan []string) {
    aSlice := make([]string, 100)

    for _,v := range list {
        if mf.checkFindRet(v) {
            aSlice = append(aSlice,v)
        }
    }
    aChan <- aSlice
}

func (mf *FindList) getFileList() []string {
    adir := "/Users/kang/Documents/GoProject"
    dir_list,e := IoUtil.ReadDir(adir)
    dirlist := make([]string, 30)
    if e != nil {
        fmt.Println("read dir error")
        return dirlist
    }
    for _,v := range dir_list {
        fileStr := strings.Trim(v.Name()," ")
        if len(fileStr) == 0 {
            continue
        }
        fileName := adir + "/" + fileStr
        _,err := os.Stat(fileName)
        if err == nil || os.IsExist(err) {
            dirlist = append(dirlist,fileName)
        }
    }
    return dirlist
}

func main() {

    finder := NewFindList(20)

    aList := finder.getFileList()
    aListLen := len(aList)
    step := (int)(aListLen / 8)

    fmt.Println(step,aListLen)

    //分配新的slice
    newSlice := make([][]string, 8)

    chanArr := make([]chan []string, 8)

    j := 0
    for i := 0; i < aListLen; i = i + step {
        chanArr[j] = make(chan []string)
        newSlice[j] = aList[i:(i + step)]
        go finder.GetRet(newSlice[j],chanArr[j])
        j++
        fmt.Println("#")
    }

    strList := make([]string, 30)
    for _,v := range chanArr {
        values := <-v
        for _,v1 := range values {

            if len(v1) == 0 {
                continue
            }
            fmt.Println(v1)
            strList = append(strList,v1)
        }
    }
    fmt.Println(len(strList))

    /* c := make([]chan string,8) for i := 0; i < 3; i++ { c[i] = make(chan string) //go aFunc("a1",c[i]) } fmt.Println(finder.ListData) */
}
原文链接:https://www.f2er.com/go/188764.html

猜你在找的Go相关文章