Java には Exchanger クラス ( https://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Exchanger.html ) があります。C ++でそのようなものを実装する方法(ブーストを使用)?
2001 次
3 に答える
1
最善の方法は、Java 自体の実装を理解し、ブースト スレッド クラスを使用して再実装することです。
于 2010-07-09T05:55:13.373 に答える
0
さて、これが競合状態をクリーンアップする 2 番目の試みです。2 つ以上のスレッドが 1 つのエクスチェンジャー オブジェクトを使用しようとすると非効率になりますが、それは非常にまれなケースであるため、それを受け入れることができると思います。
#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 に答える