Sobes.tech
Junior — Middle

Kas olete oma projektides kasutanud sync.Cond abil sünkroniseerimismehhanismi?

sobes.tech AI

Vastus AI-lt

In Go projects, I have 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 specific 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 signal
	}
	fmt.Println("Goroutine is ready")
	mu.Unlock()
}

This approach is useful when you need finer control over state and synchronization than just using channels.