1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
/***************************************** Semaphore.h Copyright (c) 2017 David Feng Distributed under the MIT License. *****************************************/ #ifndef SEMAPHORE_H #define SEMAPHORE_H #include <boost/thread/condition.hpp> #include <boost/thread/mutex.hpp> #include <limits> /* Semaphore: to limit a certain number of threads' access to a resource a thread will be blocked by wait() when the number of threads that have access to a resource reaches the limit a thread will signal() one other thread that is blocked by wait() to access to a resource when it releases access to the resource */ class Semaphore { boost::mutex m_mutex; boost::condition m_condition; unsigned long m_count; public: explicit Semaphore(unsigned long count) : m_count(count) { } void Wait()//called when a thread entering the shared critical section { boost::mutex::scoped_lock lock(m_mutex); while (m_count == 0) m_condition.wait(lock); --m_count; } void Signal()//called when a thread leaving the shared critical section { boost::mutex::scoped_lock lock(m_mutex); ++m_count; m_condition.notify_one(); } }; #endif |
Copyright © 2016-2020 Qualgame, LLC