0

I'm having a hard time understanding livelock.

For example, is this a livelock?

// Task 1
void task1() {
  // Wait for event A with a timeout
  while (getEventUntil(A, 1000)) {
    // Fill the buffer
    fillBuf();
    // Set event B
    setEvent(B);
  }
}

// Task 2
void task2() {
  // Wait for event B with a timeout
  while (getEventUntil(B, 1000)) {
    // Consume the buffer
    consumeBuf();
    // Set event A
    setEvent(A);
  }
}

Here fillBuf and consumeBuf will never be executed, instead the while loop will loop endlessly for both tasks.

d4mb
  • 33
  • 6
  • Here a livelock is just slightly different from a deadlock (where the threads sleep, wait on each other). Here they are "live", but task1 is waiting for event A, which will not happen until it has itself set event B. – BoP Jun 25 '23 at 20:28
  • Thanks! What would be a better example of a livelock? – d4mb Jun 25 '23 at 20:38
  • 2
    [Deadlock, Livelock and Starvation](https://www.baeldung.com/cs/deadlock-livelock-starvation) – Ted Lyngmo Jun 25 '23 at 20:46
  • 2
    A livelock would be like waiting in the queue at the counter, and other people skipping queue in front of you (forever). The system as a whole is still serving customers but you don't get a chance. In a deadlock two (or more tasks) need multiple resources and both tasks have already partially claimed resources, and now neither task can continue. (Good rule in multithreading : claim all resoureces in one step or none to avoid this) – Pepijn Kramer Jun 25 '23 at 20:47
  • 1
    https://stackoverflow.com/a/35129823/4454124 – mnistic Jun 25 '23 at 20:48

0 Answers0