Go Language Foundation - Goroutine - Thread Security in Shared Memory

Goroutines are lighter threads

Threads are more efficient than in Java

Co operative grammar
go func() {
   //...
}()

Once the code in the main goroutine is executed, the current Go program will be terminated, regardless of whether other goroutines are already running.

Let the master goroutine wait for other goroutines:
for i := 0; i < 10; i++ {
    go func() {
        fmt.Println(i)
    }()
}
time.Sleep(time.Millisecond * 1000)
//The goroutine completion time is likely to be less than the set waiting time, which will result in extra waiting time.
How can we get goroutine to execute the next goroutine immediately after it is executed?

WaitGroup provided by go language can achieve this function.

Code modification:

var wg sync.WaitGroup
for i := 0; i < 10; i++ {
    wg.Add(1)//Add a wait for each start of a collaboration
    go func() {
        fmt.Println(i)
        wg.Done()//Tell the coalition that the pending transaction has been completed
    }()
}
/*
So we don't have to set the waiting time, but the output is like this: 374,8,8,9,10,10,10, obviously this way can't guarantee goroutine to get a unique integer.
*/
How to ensure that each thread gets a unique number?

Code modification:

var wg sync.WaitGroup
for i := 0; i < 10; i++ {
    wg.Add(1)//Add a wait for each start of a collaboration
    go func(j int) {//You can name j arbitrarily if it's just a parameter.
        fmt.Println(j)
        wg.Done()//Tell the coalition that the pending transaction has been completed
    }(i)//Pass the parameter i to the parameter j
}
//Implementation results: 0 2 1 6 3 4 5 8 7 9

We pass the value of i to j, the change of i will not affect the value of j, so the output is unique.

Shared memory thread security
func TestCounter(t *testing.T) {
    counter := 0
    for i := 0; i < 5000; i++ {
        go func() {
            counter++
        }()
    }
    time.Sleep(1 * time.Second)
    t.Logf("counter = %d", counter)
}
//Execution results: Thread security issues occurred in 4760

Like most languages, go supports locking to ensure thread security:

func TestCounterWaitGroup(t *testing.T) {
    var mut sync.Mutex//Create lock objects
    var wg sync.WaitGroup
    counter := 0
    for i := 0; i < 5000; i++ {
        wg.Add(1)//Add a wait for each start of a collaboration
        go func() {
            defer func() {
                mut.Unlock()//Release lock
            }()
            mut.Lock()//Opening lock
            counter++
            wg.Done()//Tell the coalition that the pending transaction has been completed
        }()
    }
    wg.Wait()//Waiting for Association
    t.Logf("counter = %d", counter)

}

Code words are not easy. If they are helpful to you, please pay attention to them.

QQ Group: 894109590

Keywords: Go Java less

Added by andriy on Thu, 03 Oct 2019 05:43:28 +0300