dongqiu8375 2017-02-05 01:15
浏览 304
已采纳

Golang多个goroutine通过引用共享相同的变量

I am trying to run multiple goroutines that modify the same variable passed by reference.

But I am sure the way I have implemented this is functionally incorrect. Even though it seems to be working in my tests, I have a feeling this pattern would end the parent function when the first goroutine completes if the second goroutine takes considerably longer to run than the first one.

I would like your input/suggestions/advice.

package auth

import (
    "regexp"

    zxcvbn "github.com/nbutton23/zxcvbn-go"
    "golang.org/x/net/context"
)

type AuthService struct{}

func NewAuthService() *AuthService {
    return &AuthService{}
}

func (this *AuthService) ValidateCredentials(ctx context.Context, req *ValidateCredentialsRequest) (*ValidateCredentialsResponse, error) {
    c := make(chan *ValidateCredentialsResponse)

    go validatePassword(req.GetPassword(), c)
    go validateUsername(req.GetUsername(), c)

    c <- &ValidateCredentialsResponse{IsValid: true}

    return <-c, nil
}

func validateUsername(email string, c chan *ValidateCredentialsResponse) {
    for {
        res := <-c

        if email == "" {
            res.IsValid = false
            res.Username = "Please provide your email address."
        } else if len(email) > 128 {
            res.IsValid = false
            res.Username = "Email address can not exceed 128 characters."
        } else if !regexp.MustCompile(`.+@.+`).MatchString(email) {
            res.IsValid = false
            res.Username = "Please enter a valid email address."
        }

        c <- res
    }
}

func validatePassword(password string, c chan *ValidateCredentialsResponse) {
    for {
        res := <-c

        if password == "" {
            res.IsValid = false
            res.Password = "Please provide your password."
        } else {
            quality := zxcvbn.PasswordStrength(password, []string{})
            if quality.Score < 3 {
                res.IsValid = false
                res.Password = "Your password is weak."
            }
        }

        c <- res
    }
}
  • 写回答

1条回答 默认 最新

  • duanhe6799 2017-02-05 02:47
    关注

    Are you sure you need goroutines to perform simple validations? Anyway the code you have written uses goroutines, but they are not running in parallel.

    What's going on in your code: you create non-buffered channel and put CredentialResponse variable into it. Then one goroutine (any of two) reads variable from channel, performs some actions, and puts variable back to the channel. While first goroutine was doing some actions, second one was just waiting for a value from a channel.

    So your code uses goroutines, but it can hardly be called parallel.

    You may want to use goroutines if you need some heavy operations to validate data: io ops, or CPU, but in case of CPU you need specify GOMAXPROCS>1 to get some performance gain.

    If I'd wanted to use goroutines for validation, I'd have written smth like it:

    func validateCredentials(req *ValidateCredentialsRequest){
        ch := make(chan bool, 2)
        go func(name string){
        // ... validation code
            ch <- true // or false
    
        }(req.GetUsername())
    
        go func(pwd string){
        // ... validation code
            ch <- true // or false
        }(req.GetPassword())
    
        valid := true
        for i := 0; i < 2; i++ {
            v := <- result
            valid = valid && v
        }
    
        // ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。