{"id":98,"date":"2012-07-18T18:04:00","date_gmt":"2012-07-18T16:04:00","guid":{"rendered":"http:\/\/pit-claudel.fr\/clement\/blog\/?p=98"},"modified":"2013-11-16T10:57:30","modified_gmt":"2013-11-16T09:57:30","slug":"a-safer-way-to-implement-boolean-flags","status":"publish","type":"post","link":"https:\/\/pit-claudel.fr\/clement\/blog\/a-safer-way-to-implement-boolean-flags\/","title":{"rendered":"A safer way to implement boolean flags"},"content":{"rendered":"<h2>Introduction<\/h2>\n<p>Boolean flags are commonly used to disable a block of code while another is running: for example,<\/p>\n<div class=\"left\">\n<pre class=\"brush: csharp; title: C#; notranslate\" title=\"C#\">\r\n  private bool in_use;\r\n  \r\n  private void Process() {\r\n    in_use = true;\r\n    (...)\r\n    in_use = false;\r\n  }\r\n  \r\n  private void OnEvent() {\r\n    if (in_use)\r\n      return;\r\n      \r\n    (...)\r\n  }\r\n<\/pre>\n<\/div>\n<div class=\"right\">\n<pre class=\"brush: vb; title: VB.Net; notranslate\" title=\"VB.Net\">\r\n  Private InUse As Boolean;\r\n  \r\n  Private Sub Process()\r\n    InUse = True\r\n    (...)\r\n    InUse = False\r\n  End Sub\r\n  \r\n  Private Sub Process()\r\n    If InUse Then Return\r\n    \r\n    (...)\r\n  End Sub\r\n<\/pre>\n<\/div>\n<hr class=\"clear\" \/>\nThis design has a major drawback : <code>in_use<\/code> blocks cannot be nested, since nesting two such blocks will turn <code>in_use<\/code> to <code>false<\/code> too early. In the following excerpt, the <code>(...)<\/code> section in the <code>Process<\/code> function will not run correctly, because <code>in_use<\/code> will have been set to <code>false<\/code> when it runs.<\/p>\n<div class=\"left\">\n<pre class=\"brush: csharp; title: C#; notranslate\" title=\"C#\">\r\n  private void Process() {\r\n    in_use = true;\r\n    Action1();\r\n    Action2();\r\n    (...) \/\/ in_use == false here (!)\r\n    in_use = false;\r\n  }\r\n\r\n  private void Action1() {\r\n    in_use = true;\r\n    (...)\r\n    in_use = false;\r\n  }\r\n\r\n  private void Action2() {\r\n    in_use = true;\r\n    (...)\r\n    in_use = false;\r\n  }\r\n<\/pre>\n<\/div>\n<div class=\"right\">\n<pre class=\"brush: vb; title: VB.net; notranslate\" title=\"VB.net\">\r\n  Private Sub Process()\r\n    InUse = True\r\n    Action1()\r\n    Action2()\r\n    (...) ' InUse = False here (!)\r\n    InUse = False\r\n  End Sub\r\n\r\n  Private Sub Action1()\r\n    InUse = True\r\n    (...)\r\n    InUse = False\r\n  End Sub\r\n\r\n  Private Sub Action2()\r\n    InUse = True\r\n    (...)\r\n    InUse = False\r\n  End Sub\r\n<\/pre>\n<\/div>\n<hr class=\"clear\" \/>\nSuch errors are difficult to spot in large applications, and often lead to hard-to-track bugs.<\/p>\n<p><!--more--><\/p>\n<h2>Robust boolean flags<\/h2>\n<p>A useful trick in such cases is to replace your boolean flags with boolean properties, linked to a counter : every time you set <code>in_use<\/code> to <code>true<\/code>, the counter is incremented; every time you set it to <code>false<\/code>, the counter is decremented. Retrieving <code>in_use<\/code> returns <code>true<\/code> when the counter is greater than 0, and <code>false<\/code> otherwise. That&#8217;s somewhat similar to the way semaphores work in parallel programming.<\/p>\n<div class=\"left\">\n<pre class=\"brush: csharp; title: C#; notranslate\" title=\"C#\">\r\n  using System.Diagnostics;\r\n\r\n  private int users_count = 0;\r\n\r\n  public bool in_use {\r\n    get { \r\n      return users_count &gt; 0;\r\n    }\r\n\r\n    set {\r\n      users_count += (value ? 1 : -1);\r\n      Debug.Assert(users_count &gt;= 0);\r\n    }\r\n  }\r\n<\/pre>\n<\/div>\n<div class=\"right\">\n<pre class=\"brush: vb; title: VB.net; notranslate\" title=\"VB.net\">\r\n  Imports System.Diagnostics\r\n  \r\n  Private UsersCount As Integer\r\n\r\n  Public Property InUse As Boolean\r\n    Get\r\n      Return UsersCount &gt; 0\r\n    End Get\r\n\r\n    Set(value As Boolean)\r\n      UsersCount += If(value, 1, -1)\r\n      Debug.Assert(UsersCount &gt;= 0)\r\n    End Set\r\n  End Property\r\n<\/pre>\n<\/div>\n<hr class=\"clear\" \/>\n<p>You can now nest <code>in_use<\/code> blocks safely.<\/p>\n<h3>Going further<\/h3>\n<p>The previous construct is not thread-safe, and might end up in an inconsistent state if an exception occurs in the body of an <code>in_use<\/code> block (<code>in_use<\/code> will never be set to <code>false<\/code> if an exception occurs in an <code>in_use<\/code> block). <\/p>\n<p>We solve both problems by declaring a <code>Flag<\/code> class which allows for the following construct:<\/p>\n<pre class=\"brush: csharp; title: C#; notranslate\" title=\"C#\">\r\n  private void Process() {\r\n    using (Flag flag = new Flag(\"custom name\")) {\r\n      (...)\r\n    }\r\n  }\r\n  \r\n  private void OnEvent() {\r\n    if (Flag.InUse(\"custom name\"))\r\n      return;\r\n      \r\n    (...)\r\n  }\r\n<\/pre>\n<pre class=\"brush: vb; collapse: true; light: false; title: VB.Net implementation; toolbar: true; notranslate\" title=\"VB.Net implementation\">\r\n  Private Sub Process()\r\n    Using flag As New Flag(\"custom name\")\r\n      (...)\r\n    End Using\r\n  End Sub\r\n  \r\n  Private Sub OnEvent()\r\n    If Flag.InUse(\"custom name\") Then Return\r\n\r\n    (...)\r\n  End Sub\r\n<\/pre>\n<p>Here is the implementation; the Flag class exposes one static method, <code>InUse(string)<\/code>, which returns whether determine whether a resource designated by a string is in use. The <code>Flag<\/code> constructor registers a new user by incrementing the <code>flag_users<\/code> counter, while the destructor accordingly decrements the <code>flag_users<\/code> counter.<\/p>\n<pre class=\"brush: csharp; title: C#; notranslate\" title=\"C#\">\r\n  class Flag : IDisposable {\r\n    string name;\r\n    private static Dictionary&lt;string, int&gt; flag_users = new Dictionary&lt;string,int&gt;();\r\n\r\n    public static bool InUse(string name) {\r\n      lock (flag_users)\r\n        return (flag_users.ContainsKey(name) &amp;&amp; flag_users&#x5B;name] &gt; 0);\r\n    }\r\n\r\n    public Flag(string name) {\r\n      this.name = name; \r\n\r\n      lock (flag_users) {\r\n        if (!flag_users.ContainsKey(name))\r\n          flag_users.Add(name, 0);\r\n\r\n        flag_users&#x5B;name] += 1;\r\n      }\r\n    }\r\n  \r\n    public void Dispose() {\r\n      lock (flag_users)\r\n        flag_users&#x5B;name] -= 1;\r\n    }\r\n  }\r\n<\/pre>\n<pre class=\"brush: vb; collapse: true; light: false; title: VB.Net implementation; toolbar: true; notranslate\" title=\"VB.Net implementation\">\r\n  Class Flag\r\n    Implements IDisposable\r\n\r\n    Private Name As String\r\n    Private Shared FlagUsersCount As New Dictionary(Of String, Integer)()\r\n\r\n    Public Shared Function InUse(name As String) As Boolean\r\n      SyncLock FlagUsersCount\r\n        Return (FlagUsersCount.ContainsKey(name) AndAlso FlagUsersCount(name) &gt; 0)\r\n      End SyncLock\r\n    End Function\r\n\r\n    Public Sub New(Name As String)\r\n      Me.Name = Name\r\n\r\n      SyncLock FlagUsersCount\r\n        If Not FlagUsersCount.ContainsKey(Name) Then\r\n          FlagUsersCount.Add(Name, 0)\r\n        End If\r\n\r\n        FlagUsersCount(Name) += 1\r\n      End SyncLock\r\n    End Sub\r\n\r\n    Public Sub Dispose() Implements System.IDisposable.Dispose\r\n      SyncLock FlagUsersCount\r\n        FlagUsersCount(Name) -= 1\r\n      End SyncLock\r\n    End Sub\r\n  End Class\r\n<\/pre>\n<p><strong>How do you implement your own boolean flags? Post examples in the comments!<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>This article presents a safe way to implement boolean flags (used to notify a thread that a resource is in use), eg. to disable events while running a background task.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[16,17,14,22],"tags":[18,19,23],"_links":{"self":[{"href":"https:\/\/pit-claudel.fr\/clement\/blog\/wp-json\/wp\/v2\/posts\/98"}],"collection":[{"href":"https:\/\/pit-claudel.fr\/clement\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/pit-claudel.fr\/clement\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/pit-claudel.fr\/clement\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/pit-claudel.fr\/clement\/blog\/wp-json\/wp\/v2\/comments?post=98"}],"version-history":[{"count":5,"href":"https:\/\/pit-claudel.fr\/clement\/blog\/wp-json\/wp\/v2\/posts\/98\/revisions"}],"predecessor-version":[{"id":653,"href":"https:\/\/pit-claudel.fr\/clement\/blog\/wp-json\/wp\/v2\/posts\/98\/revisions\/653"}],"wp:attachment":[{"href":"https:\/\/pit-claudel.fr\/clement\/blog\/wp-json\/wp\/v2\/media?parent=98"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/pit-claudel.fr\/clement\/blog\/wp-json\/wp\/v2\/categories?post=98"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/pit-claudel.fr\/clement\/blog\/wp-json\/wp\/v2\/tags?post=98"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}