当前位置:编程学习 > VC++ >>

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

 

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

 

Concurrency::reader_writer_lock::scoped_lock_read boost::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()); 

        } 

    } 

}  www.zzzyk.com

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 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,