C++0x 正在获得多线程支持,该支持包括一个名为 condition_variable_any 的新类型:
class condition_variable_any
{
public:
condition_variable_any();
~condition_variable_any();
condition_variable_any(const condition_variable_any&) = delete;
condition_variable_any& operator=(const condition_variable_any&) = delete;
void notify_one();
void notify_all();
template <class Lock>
void wait(Lock& lock);
template <class Lock, class Predicate>
void wait(Lock& lock, Predicate pred);
template <class Lock, class Clock, class Duration>
cv_status
wait_until(Lock& lock,
const chrono::time_point<Clock, Duration>& abs_time);
template <class Lock, class Clock, class Duration, class Predicate>
bool
wait_until(Lock& lock,
const chrono::time_point<Clock, Duration>& abs_time,
Predicate pred);
template <class Lock, class Rep, class Period>
cv_status
wait_for(Lock& lock,
const chrono::duration<Rep, Period>& rel_time);
template <class Lock, class Rep, class Period, class Predicate>
bool
wait_for(Lock& lock,
const chrono::duration<Rep, Period>& rel_time,
Predicate pred);
};
这里有一个关于如何实现 condition_variable_any 的解释:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2406.html#gen_cond_var
但在此链接中,它被命名为 gen_cond_var。condition_variable_any 的神奇之处在于它会等待任何具有 lock() 和 unlock() 成员的东西。一旦你有了condition_variable_any,那么你只需要一个rwlock。上面的链接还介绍了 shared_mutex 和 shared_lock 并显示了执行您想要的示例代码:
std::tr2::shared_mutex mut;
std::gen_cond_var cv;
void wait_in_shared_ownership_mode()
{
std::tr2::shared_lock<std::tr2::shared_mutex> shared_lk(mut);
// mut is now shared-locked
// ...
while (not_ready_to_proceed())
cv.wait(shared_lk); // shared-lock released while waiting
// mut is now shared-locked
// ...
} // mut is now unlocked
void wait_in_unique_ownership_mode()
{
std::unique_lock<std::tr2::shared_mutex> lk(mut);
// mut is now unique-locked
// ...
while (not_ready_to_proceed())
cv.wait(lk); // unique-lock released while waiting
// mut is now unique-locked
// ...
} // mut is now unlocked
上述文件有些过时了。这里有 shared_mutex / shared_lock 的更新实现和描述:
http://howardhinnant.github.io/shared_mutex http://howardhinnant.github.io/shared_mutex.cpp
所有这些都是在 POSIX pthreads 之上实现的。我希望将共享锁定的内容写入 C++ 技术报告 (tr2),但当然不能保证这一点。