dongre6404 2015-01-23 00:46
浏览 22
已采纳

Go lang中的线程同步

I want to understand a bit more about how synchronisation of threads works in go. Below here I've have a functioning version of my program which uses a done channel for syncronization.

package main

import (
    . "fmt"
    "runtime"
)

func Goroutine1(i_chan chan int, done chan bool) {
    for x := 0; x < 1000000; x++ {
        i := <-i_chan
        i++
        i_chan <- i
    }
    done <- true
}
func Goroutine2(i_chan chan int, done chan bool) {
    for x := 0; x < 1000000; x++ {
        i := <-i_chan
        i--
        i_chan <- i
    }
    done <- true
}

func main() {
    i_chan := make(chan int, 1)
    done := make(chan bool, 2)
    i_chan <- 0

    runtime.GOMAXPROCS(runtime.NumCPU())
    go Goroutine1(i_chan, done)
    go Goroutine2(i_chan)
    <-done
    <-done
    Printf("This is the value of i:%d
", <-i_chan)
}

However when I try to run it with out any synchronisation. Using a wait statement and no channel to specify when it's done so no synchronisation.

const MAX = 1000000

func Goroutine1(i_chan chan int) {
    for x := 0; x < MAX-23; x++ {
        i := <-i_chan
        i++
        i_chan <- i
    }
}

func main() {
    i_chan := make(chan int, 1)
    i_chan <- 0
    runtime.GOMAXPROCS(runtime.NumCPU())
    go Goroutine1(i_chan)
    go Goroutine2(i_chan)
    time.Sleep(100 * time.Millisecond)
    Printf("This is the value of i:%d
", <-i_chan)
}

It'll print out the wrong value of i. If you extend the wait for let say 1 sec it'll finish and print out the correct statement. I kind of understand that it has something with both thread not being finished before you print what's on the i_chan I'm just a bit curious about how this works.

  • 写回答

1条回答 默认 最新

报告相同问题?

悬赏问题

  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗