Golang Concurrent Resource Competition (mutex)

Source: Internet
Author: User
Concurrency itself is not complicated, but because of the problem of resource competition, it makes it complicated to develop a good concurrency program, because it can cause a lot of puzzling problems.
Package Mainimport ("FMT"    "Runtime"    "Sync")var(count int32 wg Sync.) Waitgroup) Func main () {WG. ADD (2) go Inccount () go Inccount () WG. Wait () fmt. Println (count)}func Inccount () {defer WG. Done () forI: =0; I <2; i++{value:=count Runtime. Gosched () value++Count=Value}}

This is an example of a resource competition. We can run this program more than once, and we will find that the result can be 2 or 3 or 4. Because the shared resource count variable does not have any synchronization protection, two goroutine will read and write to it, causing the result to be overwritten with the results that have been calculated, resulting in incorrect results. Here we demonstrate one possible, two goroutine we call G1 and G2 for the time being.

G1 read to count is 0.

Then G1 paused, switched to G2 run, G2 read to count also for 0.

G2 pause, switch to G1,G1 to Count+1,count to 1.

G1 paused, switching to G2,G2 has just obtained a value of 0, +1 for it, and the last assignment to count or 1.

Have noticed, just G1 to count+1 the result is G2 to cover, two goroutine are +1 or 1.

No longer continue to demonstrate, the result has been wrong, two goroutine each other coverage results. We are here runtime.Gosched() to let the current goroutine pause the meaning. Return the execution queue and let the other waiting goroutine run, in order to let us demonstrate that the results of the competition for resources are more pronounced. Note that this will also involve CPU problems, multi-core will be parallel, then the effect of resource competition is more obvious.

So our reading and writing of the same resource must be atomized, that is, only one goroutine can read and write to the shared resource at the same time.

The problem of shared resource competition is very complex and difficult to detect, but the go provides a tool to help us check, this is the go build -race command. We execute this command in the current project directory, generate a file that can be executed, and then run the executable file to see the printed detection information.

Go build-race

Add a -race flag, so that the generated executable program comes with the ability to detect the competition of resources. Below we run, also run at the terminal.

./hello

The executable file name I generated here is hello , so it works. At this point, we look at the output of the terminal test results.

Hello./Hello==================Warning:data Raceread at0x0000011a5118by Goroutine7: Main.inccount ()/users/xxx/code/go/src/flysnow.org/hello/main.go: -+0x76Previous Write at0x0000011a5118by Goroutine6: Main.inccount ()/users/xxx/code/go/src/flysnow.org/hello/main.go: -+0x9aGoroutine7(running) created At:main.main ()/users/xxx/code/go/src/flysnow.org/hello/main.go: -+0x77Goroutine6(finished) created At:main.main ()/users/xxx/code/go/src/flysnow.org/hello/main.go: -+0x5f==================4Found1Data Race (s)

Look, find a resource competition, even in that line of code out of the problem, are marked out. Goroutine 7 reads the shared resource in line 25, value := count while Goroutine 6 is modifying the shared resource in line 28, count = value and the two goroutine are started from the main function, in 16, 17 rows, through the GO keyword.

Now that we know about the problem of shared resource competition, because there are two or more goroutine to read and write to it, we just need to make sure that only one goroutine read and write. Now let's look at the traditional solution to resource competition-locking resources.

The go language provides some of the functions in the atomic package and the Sync Pack to synchronize the shared resources, and we'll just look at sync:

The sync package provides a mutex lock that gives us the flexibility to control the code, with only one goroutine access, which is called the critical section of the code range controlled by the sync mutex. The Code of the critical section, at the same time, can only be accessed again by a goroutine. Just for that example, we can change that.

Package Mainimport ("FMT"    "Runtime"    "Sync")var(count int32 wg Sync.) Waitgroup Mutex sync. Mutex) Func main () {WG. ADD (2) go Inccount () go Inccount () WG. Wait () fmt. Println (count)}func Inccount () {defer WG. Done () forI: =0; I <2; i++{mutex.} Lock () Value:=count Runtime. Gosched () value++Count=The value mutex. Unlock ()}}

instance, a new mutex is declared mutex sync.Mutex . This mutex has two methods, one is, the other mutex.Lock() is mutex.Unlock() . The area between the two is a critical section, and the Code for the critical section is safe.

In the example we first call mutex.Lock() the code that has the competition resource lock, so when a goroutine into this area, the other goroutine will not come in, can only wait, until the call to mutex.Unlock() release the lock.

This is a more flexible approach, allowing code writers to arbitrarily define the range of code that needs to be protected, which is the critical section. In addition to atomic functions and mutexes, go also provides us with the ability to sync more easily in multiple goroutine, which is channel Chan.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.