golang 怎么并发

已邀请:

heramerom

赞同来自: whutchao itstudying

func TodoWork(){
    ch := make(chan interface{}, 1024)
    defer close(ch)
    for key ,value := range allMap{
        go  processOneByOne(key , value, ch)
    }

    for {
        value, ok := <- ch
        if !ok {
            panic ()
        }
        println(value)
    }
}

func processOneByOne(key string, value []interface{}, ch chan interface{}) {
    // do something
    ch <- result
}

whutchao

赞同来自:

1、TodoWork函数如果在多线程环境下调用,ch通道里面的结果会不会存在数据竞争的情况? 比如

func ceshi(){

    for _ ,elem :=  range  alist {
        TodoWork()   
    }
}

itstudying

赞同来自:

根据 heramerom 的基础上小小修改了下,控制 TodoWork 函数的正常退出

func TodoWork(allMap map[string][]interface{}) {
    ch := make(chan interface{}, 1024)
    wg := sync.WaitGroup{}
    wg.Add(len(allMap))

    go func() {
        defer close(ch)
        wg.Wait()
    }()
    for key, value := range allMap {
        go func() {
            defer wg.Done()
            processOneByOne(key, value, ch)
        }()
    }

    for {
        value, ok := <-ch
        if !ok {
            panic ()
        }
        println(value)
    }
}

func processOneByOne(key string, value []interface{}, ch chan interface{}) {
    // do something
    ch <- result 
}

要回复问题请先登录注册