gcc4.7编译thread程序

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

 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

 

 

 

 

转载于:https://www.cnblogs.com/lgzdlmu1985/archive/2012/11/29/2794035.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值