$include_dir="/home/hyper-archives/boost-users/include"; include("$include_dir/msg-header.inc") ?>
From: Roland Schwarz (roland.schwarz_at_[hidden])
Date: 2004-12-23 02:25:35
Amerio wrote:
> Hello,
>
> I'm lacking a boost semaphore, so I tried to roll my own.
> Being carefull with threads, I present here my version, hoping you 
> gurus will spot any flaw.
>
> class sem
> {
>    sem(unsigned count): m_count(count) {}
>
>    void post()
>    {
>         boost::mutex::scoped_lock    lock(m_mutex);
>         ++m_count;
>         m_cond_.notify_one();
>    }
>
>    void wait()
>    {
>        boost::mutex::scoped_lock     lock(m_mutex);
>        while ( m_count==0 ) m_cond.wait( lock );
>        --m_count;
>    }
>
> private:
>    unsigned    m_count;
>    boost::mutex    m_mutex;
>    boost::condition    m_cond;
> };
>
> Objective : I need a semaphore to sync many readers to a single input 
> queue.
> If you know another implementation or solution to this specific 
> problem, your help is welcome.
Looks almost correct. But as you likely will have multiple waiters, I 
suggest
using m_cond_.notify_all() instead. You might also consider to obtain a book
on pthreads (if you do not already own), where you will find that the 
semaphore
is just a special case of (condvar, mutex, predicate) triple.
I also recommend to look at the "condvar" example of boost.thread, which
shows a simple queue implementation (albeit for single reader/writer).
Roland