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);
while (not_ready_to_proceed())
cv.wait(shared_lk);
}
void wait_in_unique_ownership_mode()
{
std::unique_lock<std::tr2::shared_mutex> lk(mut);
while (not_ready_to_proceed())
cv.wait(lk);
}
上述文件有些过时。这里有一个更为实用和详细的shared_mutex/shared_lock实现和描述:
http://howardhinnant.github.io/shared_mutex http://howardhinnant.github.io/shared_mutex.cpp
所有这些都是在POSIX pthreads之上实现的。我希望将共享锁定内容纳入C++技术报告(tr2)中,但当然不能保证。