FLY
Life is like riding a bicycle, to keep your balance, you must keep moving.

源代码(引用文档中例子):

 1 #include <iostream>
 2 #include <chrono>
 3 #include <thread>
 4 #include <mutex>
 5 #include <map>
 6 #include <string>
 7  
 8 std::map<std::string, std::string> g_pages;
 9 std::mutex g_pages_mutex;
10  
11 void save_page(const std::string &url)
12 {
13     // simulate a long page fetch
14     std::this_thread::sleep_for(std::chrono::seconds(2));
15     std::string result = "fake content";
16  
17     g_pages_mutex.lock();
18     g_pages[url] = result;
19     g_pages_mutex.unlock();
20 }
21  
22 int main() 
23 {
24     std::thread t1(save_page, "http://foo");
25     std::thread t2(save_page, "http://bar");
26     t1.join();
27     t2.join();
28  
29     g_pages_mutex.lock();
30     for (const auto &pair : g_pages) {
31         std::cout << pair.first << " => " << pair.second << '\n';
32     }
33     g_pages_mutex.unlock();
34 }

编译命令: 当使用C++11时,需要指定 -std=c++11,-pthread,-D_GLIBCXX_USE_NANOSLEEP三项,缺一不可。

g++ mutex.cpp -o mutex -std=c++11 -pthread -D_GLIBCXX_USE_NANOSLEEP

错误情况:

1.指定-std=c++11:

[root@localhost test]# g++ mutex.cpp -o mutex -std=c++11
mutex.cpp: In function ‘void save_page(const string&)’:
mutex.cpp:12:2: error: ‘sleep_for’ is not a member of ‘std::this_thread’

在命令中指定_GLIBCXX_USE_NANOSLEEP:

g++ mutex.cpp -o mutex -std=c++11 -D_GLIBCXX_USE_NANOSLEEP

The define _GLIBCXX_USE_NANOSLEEP is set from the gcc configuration scripts and is based on whether nanosleep is supported on the target platform.

2.当额外添加-c参数时,生成的执行文件为非执行的。手动修改为执行文件,执行时出错!!

g++ -c mutex.cpp -o mutex -std=c++11 -D_GLIBCXX_USE_NANOSLEEP

3.未指定-pthread:

g++ mutex.cpp -o mutex -std=c++11 -D_GLIBCXX_USE_NANOSLEEP

生成可执行文件mutex,执行此文件时报错:

[root@localhost test]# ./mutex
terminate called after throwing an instance of 'std::system_error'
  what():  Operation not permitted
Aborted

 

 

 

 

posted on 2012-11-29 09:53  juice_li  阅读(2891)  评论(0编辑  收藏  举报