dongyang7152 2019-05-22 09:50
浏览 85
已采纳

在不同的goroutine中替换字符串的值时是否需要互斥锁?

Do I need a mutex in this case? I am refreshing the token with a goroutine, the token is used in another goroutine. In other words, will my token be empty at some point so that the response will be a 401?

If yes, is it part of the structure c *threatq or is it a simple variable, I mean, a "standalone" one inside my code.

// IndicatorChannelIterator returns indicators from ThreatQ into a channel.
func (c *threatq) IndicatorChannelIterator() (<-chan *models.Indicator, error) {
    // Authenticate
    token, err := c.authenticate(c.clientID, c.email, c.password)
    if err != nil {
        return nil, fmt.Errorf("Error while authenticating to TQ : %s", err)
    }

    // Periodically refresh the token
    ticker := time.NewTicker(30 * time.Minute)
    go func() {
        for range ticker.C {
            token, err = c.authenticate(c.clientID, c.email, c.password)
            if err != nil {
                logrus.Errorf("Error while authenticating to TQ : %s", err)
            }
        }
    }()

    // Prepare the query
    query := &Query{}

    // Get the first page
    firstTQResponse, err := c.advancedSearch(query, token, 0)
    if err != nil {
        return nil, fmt.Errorf("Error while getting the first page from TQ : %s", err)
    }

    // Create the channel
    indicators := make(chan *models.Indicator)

    // Request the others
    go func() {
        req := 1
        total := firstTQResponse.Total
        for offset := 0; offset < total; offset += c.perPage {    
            // Search the indicators
            tqResponse, err := c.advancedSearch(query, token, offset)
            if err != nil {
                logrus.Errorf("Error while getting the indicators from TQ : %s", err)
                continue
            }

...
  • 写回答

2条回答 默认 最新

  • dongxianrang9269 2019-05-22 09:57
    关注

    The rule is simple: if a variable is accessed from multiple goroutines and at least one of them is a write, explicit synchronization is needed.

    This is true in your case: one of your goroutine writes the token variable (and also the err variable!), and another reads it, so you must synchronize access.

    Since token is not a field of the threatq structure, putting the mutex that protects it would not be wise. Always put the mutex close to the data it ought to protect.

    Some notes: as mentioned earlier, you also write and read the local err variable from multiple goroutines. You should not do this, instead create another local variable to hold the error from other goroutines (unless you want to "translfer" the error between goroutines, but this is not the case here).

    See related questions:

    Immutability of string and concurrency

    Should we synchronize variable assignment in goroutine?

    golang struct concurrent read and write without Lock is also running ok?

    Reading values from a different thread

    Why does this code cause data race?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料