Sobes.tech
Junior — Middle

Have you used synchronization mechanisms with sync.Cond in your projects?

sobes.tech AI

Answer from AI

In Go projects, I used sync.Cond to organize waiting and notification between goroutines when conditional synchronization was needed. For example, when one goroutine needs to wait until another performs a certain action or changes state.

Example of using sync.Cond:

package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	mu := sync.Mutex{}
	cond := sync.NewCond(&mu)
	ready := false

	go func() {
		time.Sleep(time.Second)
		mu.Lock()
		ready = true
		cond.Signal() // notify the waiting goroutine
		mu.Unlock()
	}()

	mu.Lock()
	for !ready {
		cond.Wait() // wait for the signal
	}
	fmt.Println("Goroutine is ready")
	mu.Unlock()
}

This approach is useful when you need more fine-grained control over state and synchronization than just using channels.