C++11 多线程

  1. #include <iostream>   
  2. #include <chrono>   
  3. #include <thread>   
  4. #include <mutex>   
  5. #include <map>   
  6. #include <string>   
  7.   
  8.   
  9.   
  10. using namespace std;  
  11. map<string, string> g_pages;  
  12. mutex g_pages_mutex;  
  13.   
  14. void save_page(const string &url)  
  15. {  
  16.     // simulate a long page fetch   
  17.     this_thread::sleep_for(chrono::seconds(1));  
  18.     string result = "fake content";  
  19.   
  20.     g_pages_mutex.lock();  
  21.     g_pages[url] = result;  
  22.     g_pages_mutex.unlock();  
  23. }  
  24.   
  25. int main()   
  26. {  
  27.     thread t1(save_page, "http://foo");  
  28.     thread t2(save_page, "http://bar");  
  29.     t1.join();  
  30.     t2.join();  
  31.   
  32.     g_pages_mutex.lock(); // not necessary as the threads are joined, but good style   
  33.     for (auto iter=g_pages.begin();iter!=g_pages.end();iter++) {  
  34.         cout << iter->first << " => " << iter->second << '\n';  
  35.     }  
  36.     g_pages_mutex.unlock(); // again, good style   
  37.     system("pause");   
  38. }  


如果你加个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才开始支持。

原文地址:https://www.cnblogs.com/hehehaha/p/6332744.html