title: More theading confusion. Why are Semaphores SO slow?
body: <p>This question is a sequel to my previous question (<a href="https://stackoverflow.com/questions/29631258/threading-in-python-what-am-i-missing">Threading in Python - What am I missing?</a>).</p>
  
  <p>Thanks to the people who indicated where the threading problem was. That problem finally solved, I enabled the semaphores and was surprised that just enabling them took the execution time of the program from a fraction of a second to 4 seconds! WOW... 3 seconds for just 80000 iterations seems frighteningly slow, even taking into account the collisions.</p>
  
  <p>The exact times:</p>
  
  <pre><code>Without semaphore      0.0167980194092 s
  With semaphore         2.76963996887 s
  </code></pre>
  
  <p>Here's the code:</p>
  
  <pre><code>import threading
  import time
  import random
  
  turnstile_names = ["N", "E", "S", "W"]
  count = 0
  sem = threading.Semaphore(1)
  
  class Incrementer(threading.Thread):
      def __init__(self, id):
          threading.Thread.__init__(self)
          self.id = id
  
      def run(self):
          global count, sem
          for i in range(20000):
              sem.acquire()
              count = count + 1
              sem.release()
  
  def main():
  
      random.seed(507129)
      incrementers = [Incrementer(name) for name in turnstile_names]
  
      for incrementer in incrementers:
          incrementer.start()
  
      # We're running!
  
      for incrementer in incrementers:
          incrementer.join()
  
      print count
      return 0
  
  if __name__ == '__main__':
      main()
  </code></pre>