临界区的类:Concurrency::critical_section; 相对应的自动加解锁类Concurrency::critical_section::scoped_lock
读写问题Concurrency::reader_writer_lock;写对应的自加解锁Concurrency::reader_writer_lock::scoped_lock;读对应的自加解锁Concurrency::reader_writer_lock::scoped_lock_read
微软这次添加的类,在boost早已经有了,我总结一下,对应关系是
Concurrency::critical_section boost::mutex
Concurrency::critical_section::scoped_lock boost::scoped_lock
Concurrency::reader_writer_lock boost::shared_mutex
Concurrency::reader_writer_lock::scoped_lock boost::uniq_lock
Concurrency::reader_writer_lock::scoped_lock_read boost::shared_lock
#include
#include
#include
#include
using namespace std;
void Write(std::list
{
for (int i(0);i<10;++i,Sleep(bAdd 50:10))
{
Concurrency::reader_writer_lock::scoped_lock _lock(rwLock);
if(bAdd)
_list.insert(_list.begin(),i);
else
{
if(_list.size())
_list.erase(_list.begin());
}
}
} www.2cto.com
void Read(std::list
{
for (int i(0);i<10;++i,Sleep(100))
{
Concurrency::reader_writer_lock::scoped_lock_read _rLock(rwLock);
for_each(_list.begin(),_list.end(),[](int i){cout<
cout< } } void fnCS(Concurrency::critical_section &io_lock) { Concurrency::critical_section::scoped_lock sLock(io_lock); for (int i(0);i<10;++i) cout<
cout< } int main(int argc, char* argv[]) { Concurrency::critical_section io_lock;//io 互斥锁 boost::thread_group tg; tg.add_thread(new boost::thread(fnCS,boost::ref(io_lock))); tg.add_thread(new boost::thread(fnCS,boost::ref(io_lock))); tg.join_all(); std::list Concurrency::reader_writer_lock rwLock; boost::thread_group tg2; tg2.add_thread(new boost::thread(Write,boost::ref(_list),boost::ref(rwLock),true));//添加 tg2.add_thread(new boost::thread(Read,boost::ref(_list),boost::ref(rwLock)));//读取 tg2.add_thread(new boost::thread(Write,boost::ref(_list),boost::ref(rwLock),false));//删除 tg2.add_thread(new boost::thread(Read,boost::ref(_list),boost::ref(rwLock)));//读取 tg2.join_all();//等待全部结束 }; 摘自 王继的技术博客