C ++ multithreading. Part of iterater is replaced by auto and mutex is used.

Source: Internet
Author: User

[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 m Ain () {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");} if you add a map <string, string >:: iterater iter, if the declaration is used, auto is not needed. The preceding section also demonstrates the multithreading feature of c ++ 11. Mutex is used. (Fortunately, I learned the operating system and understood the concept of thread mutex .) Of course it can be simpler, just like C #'s foreach. (Of course I have never touched C #) the following changes: [cpp] for (auto pair: g_pages) {cout <pair. first <"=>" <pair. second <'\ n';} does not write the result. They are all the same and the implementation method is different.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.