Synchronization of the Goroutine (part I.)

Source: Internet
Author: User
! [Image] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/sync-goroutine/part1.jpeg) Assume that the Go program launches two Goroutine: "Gopackage mainimport (" FMT "" Sync ") func main () {var v int var wg sync. Waitgroup WG. ADD (2) go func () {v = 1 WG. Done ()} () go func () {fmt. Println (v) WG. Done ()} () WG. Wait ()} ' two goroutine all operate on shared variable *v*. One of the values (read operations) that assigns a new value (a write operation) while the other prints the variable. The [Waitgroup] (https://golang.org/pkg/sync/#WaitGroup) in the > *sync package is used to wait for two non-main goroutine to end. Otherwise, we can't even ensure that any of these goroutine have been started. * Because different goroutine are independent tasks, there is no implicit order between the operations they perform. In the above example, we do not know whether to print out ' 0 ' or ' 1 '. If in ' FMT. When Println ' is triggered, another goroutine has executed the assignment statement ' V = 1 ', then the output will be ' 1 '. However, everything is unknown until the program is actually executed. In other words, assignment statements and calls to ' FMT. Println ' are unordered-they are concurrent. This is not good if we cannot determine the program's behavior by looking at the source code. The GO specification introduces a partial order relationship (* pre-occurrence principle * *happen before*) for memory operations (read and write). This order allows us to infer the behavior of the program. In addition, some of the mechanisms in this language allow programmers to enforce the order of operations. In a single goroutine, all operations are in the same order as they are in the source code. "' GOWG. ADD (2) WG. Wait () "" In the above example the function calls are ordered because they are in the same goroutine--' WG. ADD (2) ' prior to ' WG. Wait () ' is executed. # # 1. Channel to communicate using channel is the heaviestThe synchronization method to be used. Sending data to the channel occurs before receiving data: "' Govar v intvar WG sync. Waitgroupwg.add (2) ch: = make (chan int) go func () {v = 1 ch <-1 WG. Done ()} () go func () {<-ch fmt. Println (v) WG. Done ()} () WG. Wait () "New thing is *ch* this channel." The output of the above program is always ' 1 ', since the received data occurs after sending data to the channel, and the sending data occurs after assigning to *v*. Assign value to *v* → Send to *ch*→ from *ch* receive → print *v* the first and third arrows are determined by the order of the same goroutine. Communication with the channel brings up the second arrow. In the end, the operations scattered in two goroutine are orderly. # # 2. The sync pack [sync] (https://golang.org/pkg/sync/) package provides the original language for synchronization. One of the solutions to our problem is [Mutex] (https://golang.org/pkg/sync/#Mutex). *sync. The variable *lock* of the mutex* type guarantees the second call to ' lock '. Lock () ' occurs at the first call to ' lock '. Unlock () ' After. Call ' Lock ' for the third time. Lock () ' occurs at the second call to ' lock '. Unlock () ' After. In general, if *m* *n*, then the *n* call ' lock '. Lock () ' occurs at the *m* call ' lock. Unlock () ' After. Let's take a look at how this knowledge is used in our sync problem: ' ' Govar v intvar WG sync. Waitgroupwg.add (2) var m sync. Mutexm.lock () go func () {v = 1 m.unlock () WG. Done ()} () go func () {M.lock () fmt. Println (v) WG. Done ()} () WG. Wait () "---in subsequent articles will show more about using the channel for communication (such as how to use the channel with the cache), [Sync] (https://golang.org/pkg/sync/) package provides a detailed explanation of what is included. Likes to help others find this article. If you want to get updates on new articles, please follow me. # # Resources-[Go memory model--go programming language] (HTTPS://GOLANG.ORG/REF/MEM) >the Go memory model specifies the conditions under which reads of a variable in one goroutine can be guaranteed to...<br>*golang.org*-[use Gopher like a *panic*] (https://medium.com/g OLANGSPEC/PANICKING-LIKE-A-GOPHER-367A9CE04BB8) > Errors while executing program on Go (after successful compilation And when OS process have been started) take the form...<br>*medium.com**[retain part of the copyright] (http://creativecommons.org/licenses /by/4.0/) **[golang] (https://medium.com/tag/golang?source=post) **[programming] (https://medium.com/tag/ Programming?source=post) **[concurrency] (https://medium.com/tag/concurrency?source=post) **[synchronization] ( Https://medium.com/tag/synchronization?source=post) **[goroutines] (https://medium.com/tag/goroutines?source= POST) * * * do you like to read? Give Michałłowicki some applause. * * Simply encourage or shout, depending on how much you like the article to applaud it.

Via:https://medium.com/golangspec/synchronized-goroutines-part-i-4fbcdd64a4ec

Author: Michałłowicki Translator: Krystollia proofreading: polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

142 Reads

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.