Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How make a function thread safe in golang

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.

like image 917
Pylinux Avatar asked Sep 10 '17 07:09

Pylinux


1 Answers

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

like image 153
Pylinux Avatar answered Sep 24 '22 08:09

Pylinux