title: Avoiding a race condition
body: <p>The following code snippet is taken page 112 of the book by Francesco Cesarini and Simon Thompson, Erlang Programming, as an illustration of a possible race condition in Erlang.</p>
  
  <pre><code>start() -&gt; 
    case whereis(db_server) of
      undefined -&gt; 
        Pid = spawn(db_server, init, []), 
        register(db_server, Pid), 
        {ok, Pid};
      Pid when is_pid(Pid) -&gt;
        {error, already_started}
    end.
  </code></pre>
  
  <p>Without copying the details verbatim, the authors explain that if two processes simultaneously execute start(), then process 1 running the "undefined" section might not complete, because process 2 causes it to be preempted. Process 2 would then run the "undefined" section to completion. Now, when process 1 resumes, db_server has already been registered by process 2, causing the its call to register() to throw a runtime error. I hope you can understand what I mean, because I don't want to filch the book's text.</p>
  
  <p>My question is how can the above <strong>exact</strong> functionality be coded to avoid the potential race condition when two processes simultaneously execute start()?</p>