C++多线程,iterater一部分用auto代替,用到mutex
[cpp]
#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#)
修改如下:
[cpp]
for (auto pair:g_pages) {
cout << pair.first << " => " << pair.second << '\n';
}
结果就不写了,都是一样的,实现方式不同而已。
补充:软件开发 , C++ ,