[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'; } 結果就不寫了,都是一樣的,實現方式不同而已。