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

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    gcc4.7编译thread程序

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/70998

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午2:35
下一篇 2023年2月9日 下午2:36

相关推荐