How to lock a function or the body of a function from being called by two threads in golang?
My use case is that I have a webserver that is calling a serial interface which can only have one caller at a time, two calls will cancel each other out by creating noise for one another on the serial line.
Easiest way is to use sync.Mutex
:
package main
import (
"fmt"
"sync"
"time"
)
var lock sync.Mutex
func main() {
go importantFunction("foo")
go importantFunction("bar")
time.Sleep(3 * time.Second)
}
func importantFunction(name string) {
lock.Lock()
defer lock.Unlock()
fmt.Println(name)
time.Sleep(1 * time.Second)
}
Here you'll see that "foo" and "bar" is printed one second apart even though they are go routines.
Go playground: https://play.golang.org/p/mXKl42zRW8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With