go.lang.best-practice.channel-guarded-with-mutex.channel-guarded-with-mutex

profile photo of semgrepsemgrep
Author
3,250
Download Count*

Detected a channel guarded with a mutex. Channels already have an internal mutex, so this is unnecessary. Remove the mutex. See https://hackmongo.com/page/golang-antipatterns/#guarded-channel for more information.

Run Locally

Run in CI

Defintion

rules:
  - id: channel-guarded-with-mutex
    pattern-either:
      - pattern: |
          $MUX.Lock()
          $VALUE <- $CHANNEL
          $MUX.Unlock()
      - pattern: |
          $MUX.Lock()
          $VALUE = <- $CHANNEL
          $MUX.Unlock()
    message: Detected a channel guarded with a mutex. Channels already have an
      internal mutex, so this is unnecessary. Remove the mutex. See
      https://hackmongo.com/page/golang-antipatterns/#guarded-channel for more
      information.
    languages:
      - go
    severity: WARNING
    metadata:
      category: best-practice
      technology:
        - go
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]

Examples

channel-guarded-with-mutex.go

package main

import (
    "fmt"
    "sync"
)

func ReadMessage() {
    messages := make(chan string)

    go func() {
        messages <- "ping"
    }()

    // ok: channel-guarded-with-mutex
    msg := <-messages
    fmt.Println(msg)
}

func ReadMessageMutex() {
    var mutex = &sync.Mutex{}
    messages := make(chan string)

    go func() {
        messages <- "ping"
    }()

    // ruleid: channel-guarded-with-mutex
    mutex.Lock()
    msg := <-messages
    mutex.Unlock()
    fmt.Println(msg)
}