Golang and Arduino

Small arduino and golang programs

Golang sync cond example

golang sync cond working example


package main

import (
    "sync"
    "time"
)

var mu = sync.Mutex{}
var sc = sync.NewCond(&mu)

var setME string

func main() {
    go func() {
        for {

        }
    }()

    // start 10 gourintines

    for i := 0; i < 10; i++ {
        go func(i int) {
            println("go routine started")
            sc.L.Lock()
            sc.Wait()
            println(setME, "release", i)
            sc.L.Unlock()

        }(i)
    }
    time.Sleep(1 * time.Second)

    // set variable and
    // signal sync.cond to release 3 random locks
    // from waiting go routines

    for i := 0; i < 3; i++ {
        sc.L.Lock()
        setME = "test signal"
        sc.Signal()
        sc.L.Unlock()
    }
    time.Sleep(2 * time.Second)

    // release all waiting go routines to use global variable
    sc.L.Lock()
    setME = "test broadcast"
    sc.Broadcast()
    sc.L.Unlock()

    time.Sleep(3 * time.Second)
}

June 24, 2020