开发者

How to implement an Exchanger (Rendezvous Pattern) in C++?

In Java, there is an Exchanger class (https://docs.oracle开发者_运维知识库.com/javase/1.5.0/docs/api/java/util/concurrent/Exchanger.html). How to implement something like that in C++ (using boost)?


The best thing to do is to understand an implementation in Java itself and try to re-implement it using boost threading classes.


Okay, here's my second attempt that cleans up the race condition. There is an inefficiency when more then two threads try to use a single exchanger object but since that is such an edge case, I think we can live with that:

#include <boost/thread.hpp>

template <class T>
class exchanger
{
public:
    exchanger()
        : ptr(0),
          state(EMPTY)
    {
    }

    void exchange(T &t)
    {
        boost::unique_lock<boost::mutex> lock(m);

        // If we arrive while an actual exchange has 
        // started but has not finished, keep out of
        // the way.
        while (state == SECOND_ARRIVED)
        {
            cv_overflow.wait(lock);
        }

        assert((state == EMPTY) || (state == FIRST_ARRIVED));

        switch (state)
        {
        case EMPTY:
            assert(!ptr);
            ptr = &t;
            state = FIRST_ARRIVED;
            while (state == FIRST_ARRIVED)
            {
                cv_main.wait(lock);
            }
            assert(state == SECOND_ARRIVED);

            ptr = 0;
            state = EMPTY;

            // Wake up any threads that happened to get
            // the mutex after the other side of the
            // exchanger notified us but before we woke up.
            cv_overflow.notify_all();
            break;

        case FIRST_ARRIVED:
            assert(ptr);
            state = SECOND_ARRIVED;
            using std::swap;
            swap(t, *ptr);
            cv_main.notify_one();
            break;
        }
    }

private:
    boost::mutex m;
    boost::condition_variable cv_main;
    boost::condition_variable cv_overflow;
    T *ptr;

    enum { EMPTY, FIRST_ARRIVED, SECOND_ARRIVED } state;
};


You should implement exchanger using a pair of barriers one for synchronization before swapping values and one for after swapping. I have done a Java conformant implementation in c++ in git below please go through the same.

https://github.com/anandkulkarnisg/Exchanger?files=1

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜