Tag Archives: threading

A safer way to implement boolean flags

Introduction

Boolean flags are commonly used to disable a block of code while another is running: for example,

  private bool in_use;
  
  private void Process() {
    in_use = true;
    (...)
    in_use = false;
  }
  
  private void OnEvent() {
    if (in_use)
      return;
      
    (...)
  }
  Private InUse As Boolean;
  
  Private Sub Process()
    InUse = True
    (...)
    InUse = False
  End Sub
  
  Private Sub Process()
    If InUse Then Return
    
    (...)
  End Sub

This design has a major drawback : in_use blocks cannot be nested, since nesting two such blocks will turn in_use to false too early. In the following excerpt, the (...) section in the Process function will not run correctly, because in_use will have been set to false when it runs.

  private void Process() {
    in_use = true;
    Action1();
    Action2();
    (...) // in_use == false here (!)
    in_use = false;
  }

  private void Action1() {
    in_use = true;
    (...)
    in_use = false;
  }

  private void Action2() {
    in_use = true;
    (...)
    in_use = false;
  }
  Private Sub Process()
    InUse = True
    Action1()
    Action2()
    (...) ' InUse = False here (!)
    InUse = False
  End Sub

  Private Sub Action1()
    InUse = True
    (...)
    InUse = False
  End Sub

  Private Sub Action2()
    InUse = True
    (...)
    InUse = False
  End Sub

Such errors are difficult to spot in large applications, and often lead to hard-to-track bugs.

Continue reading