Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use boost barrier

Tags:

c++

boost

What is boost:barrier, how to use this kind of boost method. Could you give me a clear example since I found the examples on the following:

    bool wait()
    {
        boost::mutex::scoped_lock lock(m_mutex);
        unsigned int gen = m_generation;

        if (--m_count == 0)
        {
            m_generation++;
            m_count = m_threshold;
            m_cond.notify_all();
            return true;
        }

        while (gen == m_generation)
            m_cond.wait(lock);
        return false;
    }

In the above codes: m_cond.notify_all();is to enter into other waiting threads? Could you tell me clearly about barrier functionality? Thank you.

like image 471
rahman Avatar asked Jul 10 '12 06:07

rahman


1 Answers

notify_all, notified awaiting threads.

A barrier is a simple concept. Also known as a rendezvous, it is a synchronization point between multiple threads. The barrier is configured for a particular number of threads (n), and as threads reach the barrier they must wait until all n threads have arrived. Once the n-th thread has reached the barrier, all the waiting threads can proceed, and the barrier is reset.

Simple example. value of the current will be outputed only when 3 threads call wait function on barrier.

#include <boost/thread.hpp>
#include <boost/thread/barrier.hpp>
#include <boost/bind.hpp>
#include <boost/atomic.hpp>

boost::mutex io_mutex;

void thread_fun(boost::barrier& cur_barier, boost::atomic<int>& current)
{
    ++current;
    cur_barier.wait();
    boost::lock_guard<boost::mutex> locker(io_mutex);
    std::cout << current << std::endl;
}

int main()
{
    boost::barrier bar(3);
    boost::atomic<int> current(0);
    boost::thread thr1(boost::bind(&thread_fun, boost::ref(bar), boost::ref(current)));
    boost::thread thr2(boost::bind(&thread_fun, boost::ref(bar), boost::ref(current)));
    boost::thread thr3(boost::bind(&thread_fun, boost::ref(bar), boost::ref(current)));
    thr1.join();
    thr2.join();
    thr3.join();
}
like image 97
ForEveR Avatar answered Oct 23 '22 23:10

ForEveR