0

在 Java 中,有一个 Exchanger 类(https://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Exchanger.html)。如何在 C++ 中实现类似的东西(使用 boost)?

4

3 回答 3

1

最好的办法是了解Java 本身的实现并尝试使用 boost 线程类重新实现它。

于 2010-07-09T05:55:13.373 回答
0

好的,这是我清理比赛条件的第二次尝试。当两个以上的线程尝试使用单个交换器对象时效率低下,但由于这是一种极端情况,我认为我们可以忍受:

#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;
};
于 2010-07-09T06:39:57.807 回答
0

您应该使用一对屏障来实现交换器,一个用于交换值之前的同步,一个用于交换之后的同步。我已经在下面的 git 中用 c++ 完成了一个符合 Java 的实现,请执行相同的操作。

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

于 2018-10-26T00:10:23.257 回答