Go Concurrency (ii)

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

In the previous article, we learned how goroutine and channel combine to achieve concurrency. Today we are going to learn another way of concurrency. Goroutine + Share variables.

At the same time, we can compare the differences between goroutine and threads.

Share variables refers to multiple goroutine variables that are simultaneously manipulated. At the same time, the operation will bring about the race (race condition) problem.

Race-State problem

If you know a little bit about concurrency, you can skip this section.

The problem with race is that when two or more threads (goroutine) manipulate a variable at the same time, you can't predict what's going on.

func Deposit(amount int){  balance = balance + amount}func main() {  for i := 2000; i > 0; i-- {    go Deposit(10)  }  time.Sleep(2*time.Second)  fmt.Println(balance)}

In the above code, we assume that there is a bank account with no money at the beginning. Then there are 2000 people together to save money, each 10 dollars, so the result should be 20000 yuan.

But it turned out to be less than 20000. Reason is

balance = balance + amount

is not an atomic operation. You can divide it into three steps: Read balance and amount, add two numbers, and add the result to write back to balance. Now we assume that the account has 1000 yuan, two users (go routine) completed the first step, to get balance 10000, user A to perform plus 10 write back, account remaining 10010, this time User B also write back to balance, write back the value is still 10010, so , User A's operation is overwritten.

The way to solve the race is to lock

var (  mu sync.Mutex  balance int)func Deposit(amount int){  mu.Lock()  balance = balance + amount  mu.Unlock()}func main() {  for i := 2000; i > 0; i-- {    go Deposit(10)  }  time.Sleep(2*time.Second)  fmt.Println(balance)}

Goroutine is different from thread

First, the thread usually has a fixed-size stack memory (2MB), and if your program needs to run 1000 threads at the same time, you'd better get more than 2G of memory. In addition, if the thread's stack memory is small, it may stackoverflow, and if the stack is too large, the machine may not run a few more threads. and Goroutine stack memory is not fixed, initially only 2KB, the maximum can be 1G

Let's take a look at node's thread, which overflows when the 20000 layer is called.

const test = (a) => {  if (a == 0){    return 0  }  return test(a-1)}test(20000)  //maximum call size exceeded

Take a look at Goroutine, you can run to the 20000000 floor, more than 1000 times times more than

func test(a int) int{  if a == 0{    return a  }  return test(a-1)}func main() {  test(20000000)}

Second, the thread is dispatched by the kernel, and the timer on the machine is dispatched once every fixed time. Kernel scheduling process is very slow, need to put the current state of the thread into memory, restore the state of another thread, update the scheduler state. The Goroutine Scheduler is provided by Go runtime, so it doesn't need to switch the kernel context, so it's lighter.

Thirdly, we can control the number of threads used by the Go program by setting the GOMAXPROCS environment variable (the default is the number of CPU cores)

The thread often has an identifier (an int or a pointer), and the goroutine is not identified. This also results in Golang having no way to store and get the "state" of the specified goroutine. The official explanation was "this was by design, since thread-local storage tends to be abused". In other words, Golang encourages you to write more pure code, and the return of the function should not be affected by the previous state.

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.