C++11 多线程
- #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 fetch
- this_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 style
- for (auto iter=g_pages.begin();iter!=g_pages.end();iter++) {
- cout << iter->first << " => " << iter->second << '\n';
- }
- g_pages_mutex.unlock(); // again, good style
- system("pause");
- }
如果你加个map<string,string>::iterater iter; 实现也是可以的,用了声明,就可以不用auto了。
上面的也是演示c++11的多线程特性。利用了mutex。(幸亏学了操作系统,明白了线程的互斥概念。)
当然可以更加简化,类似C#的foreach一样。(当然我没怎么接触过C#)
修改如下:
注:VS2012才支持C++11,测试过VS2010SP1也不支持C++11,看国外的网站也说VS2012才开始支持。