首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

C++11 多线程,iterater部分用auto代替,用到mutex

2013-01-28 
C++11 多线程,iterater一部分用auto代替,用到mutex#include iostream#include chrono#include thread

C++11 多线程,iterater一部分用auto代替,用到mutex

#include <iostream>#include <chrono>#include <thread>#include <mutex>#include <map>#include <string>using namespace std;map<string, string> g_pages;mutex g_pages_mutex;void save_page(const string &url){// simulate a long page fetchthis_thread::sleep_for(chrono::seconds(1));string result = "fake content";g_pages_mutex.lock();g_pages[url] = result;g_pages_mutex.unlock();}int main() {thread t1(save_page, "http://foo");thread t2(save_page, "http://bar");t1.join();t2.join();g_pages_mutex.lock(); // not necessary as the threads are joined, but good stylefor (auto iter=g_pages.begin();iter!=g_pages.end();iter++) {cout << iter->first << " => " << iter->second << '\n';}g_pages_mutex.unlock(); // again, good stylesystem("pause"); }


如果你加个map<string,string>::iterater iter; 实现也是可以的,用了声明,就可以不用auto了。

上面的也是演示c++11的多线程特性。利用了mutex。(幸亏学了操作系统,明白了线程的互斥概念。)

当然可以更加简化,类似C#的foreach一样。(当然我没怎么接触过C#)

修改如下:

for (auto pair:g_pages) {cout << pair.first << " => " << pair.second << '\n';}

 

结果就不写了,都是一样的,实现方式不同而已。

注:VS2012才支持C++11,测试过VS2010SP1也不支持C++11,看国外的网站也说VS2012才开始支持。

热点排行