douzhao7014 2016-09-09 18:28
浏览 114
已采纳

goroutine或多线程在golang中不起作用

I was trying to implement multithreading in golang. I am able to implement go routines but it is not working as expected. below is the sample program which i have prepared,

func test(s string, fo *os.File) {
    var s1 [105]int
    count :=0
    for x :=1000; x<1101;x++ {
    s1[count] = x;
        count++
    }

    //fmt.Println(s1[0])
    for i := range s1 {
        runtime.Gosched() 
        sd := s + strconv.Itoa(i)
        var fileMutex sync.Mutex
        fileMutex.Lock()
        fmt.Fprintf(fo,sd)
        defer fileMutex.Unlock()
    }
}

func main() {
    fo,err :=os.Create("D:/Output.txt")
    if err != nil {
        panic(err)
    }
    for i := 0; i < 4; i++ {
        go test("bye",fo) 

    }



}

OUTPUT - good0bye0bye0bye0bye0good1bye1bye1bye1bye1good2bye2bye2bye2bye2.... etc. the above program will create a file and write "Hello" and "bye" in the file.

My problem is i am trying to create 5 thread and wanted to process different values values with different thread. if you will see the above example it is printing "bye" 4 times.

i wanted output like below using 5 thread,

good0bye0good1bye1good2bye2....etc....

any idea how can i achieve this?

  • 写回答

1条回答 默认 最新

  • drox90250557 2016-09-09 19:02
    关注

    First, you need to block in your main function until all other goroutines return. The mutexes in your program aren't blocking anything, and since they're re-initialized in each loop, they don't even block within their own goroutine. You can't defer an unlock if you're not returning from the function, you need to explicitly unlock in each iteration of the loop. You aren't using any of the values in your array (though you should use a slice instead), so we can drop that entirely. You also don't need runtime.GoSched in a well-behaved program, and it does nothing here.

    An equivalent program that will run to completion would look like:

    var wg sync.WaitGroup
    
    var fileMutex sync.Mutex
    
    func test(s string, fo *os.File) {
        defer wg.Done()
        for i := 0; i < 105; i++ {
            fileMutex.Lock()
            fmt.Fprintf(fo, "%s%d", s, i)
            fileMutex.Unlock()
        }
    }
    
    func main() {
        fo, err := os.Create("D:/output.txt")
        if err != nil {
            log.Fatal(err)
        }
        for i := 0; i < 4; i++ {
            wg.Add(1)
            go test("bye", fo)
    
        }
        wg.Wait()
    }
    

    Finally though, there's no reason to try and write serial values to a single file from multiple goroutines, and it's less efficient to do so. If you want the values ordered over the entire file, you will need to use a single goroutine anyway.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决