This is the 19th day of my participation in the August More Text Challenge

This article appears in my column:Let’s Golang

Go language those things talk about coroutine concurrency competing resource problems

In the actual operation process, we often encounter the situation of having multiple coroutines concurrency, so when multiple coroutines are concurrent, how do coroutines compete with each other for limited resources? This article will introduce the relevant content.

Let’s take a look at the main function of the example code in this article, the two sliver coroutines. The main coroutine ends in 3 seconds.

func main(a) {
    go fun1()
    go fun2()
​
    time.Sleep(3 * time.Second)
}
​
Copy the code

Let’s take a look at what the two coroutines do.

func fun1(a){
    // Iterate over each character of the string
    for _,c:=range "Like a mouse loves rice."{
        // If Println is used here, the output will be the number of the character in the character set.
        // F is a format.
        fmt.Printf("%c\n",c)
        //runtime.Goexit()
        // Print one word every nanosecond.
        time.Sleep(time.Nanosecond)
    }
​
}
​
func fun2(a){
    for _,c := range"ReganYue"{
        fmt.Printf("%c\n",c)
        //runtime.Goexit()
        time.Sleep(time.Nanosecond)
​
    }
}
Copy the code

The fun1 function is iterated over the output “as a mouse loves rice”. Println cannot be used to loop through the string, because Println would print the number of the character in the character set.

And FMT.Printf where f stands for format.

Look at the results

R is like e g old rat A N loves Y big rice U ECopy the code

The results of the two coroutines were found to be evenly distributed. This means that the two coroutines compete fairly for resources and are equally powerful.

Fun1 runtime.goexit ()

So the output is:

R e g a N Y U ECopy the code

If you activate runtime.goexit () in fun2

So the output is:

Like a rat loves JimmyCopy the code

Because Goexit kills its Goroutine, other Goroutines are unaffected. So when the subcoroutine of fun1 is killed, it does not affect the normal operation of the subcoroutine of fun2.

If both runtime.goexit () are active in this code, then both coroutines will output only one character.

It RCopy the code

Because two coroutines are killed after one character.

If two or more coroutines access a shared resource without synchronization and attempt to read and write the shared resource at the same time. There will be competition for resources. This problem can make the program a little more complicated. This article will not discuss these complications for the time being. If you want to know, you can follow the blogger, who will introduce you later.

We can also use the go Build -race parameter to see if there is a resource race problem. The use of the Go Build -race parameter will not be covered in this blog post.