Sobes.tech
Middle+

What is livelock?

sobes.tech AI

Answer from AI

Livelock is a state similar to deadlock, but instead of blocking, threads continuously try to perform work, canceling each other's actions due to competition for resources, which leads to their inability to make progress.

Example of livelock: two threads try to acquire two resources A and B. Thread 1:

  1. Gets resource A.
  2. Tries to get resource B. If unsuccessful, releases A and retries.

Thread 2:

  1. Gets resource B.
  2. Tries to get resource A. If unsuccessful, releases B and retries.

As a result, threads may constantly release resources and try to acquire them again, without reaching a goal.

Differences from deadlock:

  • Deadlock: threads are blocked, waiting for each other.
  • Livelock: threads are actively working but not making progress.

Prevention:

  • Ordered access to resources.
  • Timeouts when attempting to acquire a resource.
  • Avoiding complex dependencies between resources.

Example pseudocode demonstrating livelock:

// Resource 1
let resource1 = NSLock()
// Resource 2
let resource2 = NSLock()

// Thread 1
DispatchQueue.global().async {
    while true {
        resource1.lock()
        if resource2.tryLock() {
            // Successfully acquired both resources
            // Perform work
            print("Thread 1 is working")
            resource2.unlock()
            resource1.unlock()
            break // Exit loop after success
        } else {
            // Failed to acquire resource2, release resource1 and retry
            resource1.unlock()
            // Small delay to avoid immediate retry
            Thread.sleep(forTimeInterval: 0.01)
        }
    }
}

// Thread 2
DispatchQueue.global().async {
    while true {
        resource2.lock()
        if resource1.tryLock() {
            // Successfully acquired both resources
            // Perform work
            print("Thread 2 is working")
            resource1.unlock()
            resource2.unlock()
            break // Exit loop after success
        } else {
            // Failed to acquire resource1, release resource2 and retry
            resource2.unlock()
            // Small delay
            Thread.sleep(forTimeInterval: 0.01)
        }
    }
}
What is livelock? — iOS - sobes.tech