EDIT: The question has nothing to do with the one that was marked as duplicate. The errors are completely different and it surprises me that people who actually have knowledge on this stuff, marked it as duplicate, as if all they wanted was to earn points...
EDIT2: The question is clear and is even in the title. I repeat it here, for even more convenience...
Are there any flags should you use for the functions of the program mentioned below?
(You only need to check the headers) For example thread needs -pthread flag.
I am a beginner in Linux C++ programming and also a beginner in multithreading. I am trying to find out what mutex exactly does and to practice on it, thus I went here and I want to compile the program over there. The problem is, I do not know which flags should I use in the compile command. I am compiling it with the command:
gcc <project_name> -o <executable_name> -std=c++14 -pthread
but I receive a bunch of errors (the compiler does not recognize chrono, mutex etc). Which flags should I use in the compilation command?
I am trying to compile it on Ubuntu 16.04 LTS (Virtual Machine from Windows 10) with gcc 6.2.0. Here is the code, for your ease:
#include <iostream>
#include <map>
#include <string>
#include <chrono>
#include <thread>
#include <mutex>
std::map<std::string, std::string> g_pages;
std::mutex g_pages_mutex;
void save_page(const std::string &url)
{
// simulate a long page fetch
std::this_thread::sleep_for(std::chrono::seconds(2));
std::string result = "fake content";
std::lock_guard<std::mutex> guard(g_pages_mutex);
g_pages[url] = result;
}
int main()
{
std::thread t1(save_page, "http://foo");
std::thread t2(save_page, "http://bar");
t1.join();
t2.join();
// safe to access g_pages without lock now, as the threads are joined
for (const auto &pair : g_pages) {
std::cout << pair.first << " => " << pair.second << '\n';
}
}