douzhao7014
2016-09-09 18:28 阅读 76
已采纳

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 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.

    点赞 评论 复制链接分享

相关推荐