Data competition analysis of global variables and local variables of Golang functions

WBOY
Release: 2023-05-21 08:19:35
Original
828 people have browsed it

Golang is a strongly typed programming language with the characteristics of efficiency, simplicity, and concurrency, so it is gradually favored by more and more developers. In the development of Golang, the global variables and local variables of functions often involve data competition issues. This article will analyze the data competition problem of global variables and local variables in Golang functions from the perspective of actual coding.

1. Data competition of global variables

Golang global variables can be accessed in all functions, so if rigorous design and coding are not carried out, data competition problems are prone to occur.

For example, in the following code, we define a global variable num and increment it in two different functions:

var num int = 0

func addNum1() {
    for i := 0; i < 1000; i++ {
        num += 1
    }
}

func addNum2() {
    for i := 0; i < 1000; i++ {
        num += 1
    }
}
Copy after login

In the above code, Both functions will increase the global variable num, which may cause data race problems. A data race occurs when two or more threads access the same shared resource simultaneously while at least one of the threads writes to the resource, resulting in undefined behavior.

The way to solve this problem is to use the Mutex type in the sync package provided by Golang. Mutex is a mutex lock. Only the thread holding the lock can access shared resources. The following is the modified code:

var num int = 0
var mutex sync.Mutex

func addNum1() {
    for i := 0; i < 1000; i++ {
        mutex.Lock()
        num += 1
        mutex.Unlock()
    }
}

func addNum2() {
    for i := 0; i < 1000; i++ {
        mutex.Lock()
        num += 1
        mutex.Unlock()
    }
}
Copy after login

In the above modified code, we implement mutually exclusive access to the global variable num through Mutex, thereby avoiding the problem of data competition.

2. Data race for local variables

Local variables are defined inside the function and can only be accessed within the function, so there are relatively few data race problems that may occur. However, there are still some issues that need to be paid attention to when using local variables.

For example, in the following code, the function getRandStr will return a random string with a length of 10:

import (
    "math/rand"
    "time"
)

func getRandStr() string {
    rand.Seed(time.Now().UnixNano())
    baseStr := "abcdefghijklmnopqrstuvwxyz0123456789"
    var randBytes []byte
    for i := 0; i < 10; i++ {
        randBytes = append(randBytes, baseStr[rand.Intn(len(baseStr))])
    }
    return string(randBytes)
}
Copy after login

In the above code, we generated a 10-digit length through a random number a random string and use it as the return value. Such code seems to have no data competition problem, but in fact, considering that the parameters in rand.Seed(time.Now().UnixNano()) change with time, if it is called in multiple goroutines at the same time This function may cause the function to return the same result, resulting in a race problem.

In order to solve this problem, we can extract rand.Seed(time.Now().UnixNano()) outside the function and only need to call it once when the program is running. The following is the modified code:

import (
    "math/rand"
    "time"
)

func init() {
    rand.Seed(time.Now().UnixNano())
}

func getRandStr() string {
    baseStr := "abcdefghijklmnopqrstuvwxyz0123456789"
    var randBytes []byte
    for i := 0; i < 10; i++ {
        randBytes = append(randBytes, baseStr[rand.Intn(len(baseStr))])
    }
    return string(randBytes)
}
Copy after login

In the above modified code, we only call rand.Seed(time.Now().UnixNano()) once through the init function to avoid multiple calls. The problem of data competition caused by calling this function at the same time in goroutine.

3. Conclusion

The above is the analysis of the data competition problem of global variables and local variables in Golang functions. To sum up, we need to follow the following principles:

  1. When reading and writing global variables, use a mutex lock to achieve mutually exclusive access to the global variable.
  2. When using local variables, please note that initialization is required when using a random number generator outside the function to avoid data competition problems caused by simultaneous access by multiple goroutines.

By following the above principles, we can avoid data race problems in Golang functions.

The above is the detailed content of Data competition analysis of global variables and local variables of Golang functions. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template