VC2010新增加对多线程的支持类

来源:互联网 发布:时光机器软件 编辑:程序博客网 时间:2024/06/05 20:09

临界区的类: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_lockboost::shared_mutex

Concurrency::reader_writer_lock::scoped_lockboost::uniq_lock<boost::shared_mutex>

Concurrency::reader_writer_lock::scoped_lock_readboost::shared_lock<boost::shared_mutex>

#include <boost/thread.hpp>#include <concrt.h>#include <iostream>#include <list>using namespace std;void Write(std::list<int> &_list,Concurrency::reader_writer_lock &rwLock,bool bAdd){    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());        }    }}void Read(std::list<int> &_list,Concurrency::reader_writer_lock &rwLock){    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<<i<<ends;});        cout<<endl;    }}void fnCS(Concurrency::critical_section &io_lock){    Concurrency::critical_section::scoped_lock sLock(io_lock);    for (int i(0);i<10;++i)        cout<<i<<ends;    cout<<endl;}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<int> _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();//等待全部结束};

VC自带的读写锁,非重入的类型,如果发生,将抛出improper_lock异常。

typedef Concurrency::reader_writer_lockrwmutex;
typedef Concurrency::reader_writer_lock::scoped_lock_readreadLock;
typedef Concurrency::reader_writer_lock::scoped_lockwriteLock;

rwmutex g_rwLock;
void testThread1()//运行木问题
{
readLock r(g_rwLock);
readLock r2(g_rwLock);
}
void testThread2()
{
writeLock w(g_rwLock);
writeLock w2(g_rwLock);//发生异常
}
void testThread3()
{
writeLock r(g_rwLock);
readLock r2(g_rwLock);//发生异常
}



原创粉丝点击