Junior — Middle
Можете объяснить, что такое Livelock в контексте программирования на Go?
sobes.tech AI
Answer from AI
Livelock is a situation in multithreaded or concurrent programs where processes or goroutines continuously react to each other, changing their state but not making progress towards completing the task. Unlike deadlock, where processes are blocked and waiting for each other, in livelock they are active but do not make progress.
In Go, this can happen if goroutines constantly try to yield to each other, for example, in a loop where they check a condition and immediately change it, preventing each other from continuing.
Example:
func livelockExample() {
var flag1, flag2 bool = true, true
go func() {
for flag1 {
// tries to yield but keeps changing the state
flag2 = false
}
}()
go func() {
for flag2 {
// also tries to yield
flag1 = false
}
}()
// neither goroutine will finish because they keep changing flags
}
To avoid livelock, proper synchronization of access to shared resources and conditions for exiting wait loops should be implemented.