Statefule Goroutines _ Golang

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

In the previous example we used explicit locking with mutexes to synchronize access to GKFX state across multiple gorout Ines. Another option is to use the built-in synchronization features of Goroutines and channels to achieve the same result. This channel-based approach aligns with Go's ideas of sharing memory by Communivating and have each piece of data owned By exactly 1 goroutine

Package Mainimport ("FMT"    "Math/rand"    "sync/atomic"    " Time") Type read0pstruct{Keyintresp Chanint}type write0pstruct{KeyintValintresp ChanBOOL}func Main () {varOPS Int64 =0reads:= Make (Chan *read0p) writes:= Make (Chan *write0p) go func () {varstate = Make (map[int]int)         for {            Select {             CaseREAD: = <-Reads:read.resp<-State[read.key] CaseWrite: = <-Writes:state[write.key]=Write.val Write.resp<-true            }        }    }()     forr: =0; R < -; r++{go func () { for{read:= &read0p{Key:rand. INTN (5), Resp:make (Chanint),} reads<-Read FMT. Println ("<-read.resp:", <-read.resp) Atomic. AddInt64 (&ops,1)            }        }()    }     forW: =0; W <Ten; w++{go func () { for{write:= &write0p{Key:rand. INTN (5), Val:rand. INTN ( -), Resp:make (ChanBOOL),} writes<-Write<-Write.resp Atomic. AddInt64 (&ops,1)}} ()} time. Sleep (time. Second) Opsfinal:= Atomic. LoadInt64 (&Ops) fmt. Println ("Ops:", opsfinal)}
329696

Summarize:

1:atomic. AddInt64 an increase in atomicity of one value

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.