Botan  1.11.15
src/lib/utils/semaphore.cpp
Go to the documentation of this file.
00001 /*
00002 * Semaphore
00003 * (C) 2013 Joel Low
00004 *
00005 * Botan is released under the Simplified BSD License (see license.txt)
00006 */
00007 
00008 #include <botan/internal/semaphore.h>
00009 
00010 // Based on code by Pierre Gaston (http://p9as.blogspot.com/2012/06/c11-semaphores.html)
00011 
00012 namespace Botan {
00013 
00014 void Semaphore::release(size_t n)
00015    {
00016    for(size_t i = 0; i != n; ++i)
00017       {
00018       std::lock_guard<std::mutex> lock(m_mutex);
00019 
00020       ++m_value;
00021 
00022       if(m_value <= 0)
00023          {
00024          ++m_wakeups;
00025          m_cond.notify_one();
00026          }
00027       }
00028    }
00029 
00030 void Semaphore::acquire()
00031    {
00032    std::unique_lock<std::mutex> lock(m_mutex);
00033    --m_value;
00034    if(m_value < 0)
00035       {
00036       m_cond.wait(lock, [this] { return m_wakeups > 0; });
00037       --m_wakeups;
00038       }
00039    }
00040 
00041 }