centos系统安装、使用C++库boost

安装包安装
1、去官网boost下载你想要的安装包
2、安装boost依赖包:yum -y install gcc gcc-c++ python python-devel libicu libicu-devel zlib zlib-devel bzip2 bzip2-devel
3、拷贝到系统

tar -zxvf boost_1_81_0.tar.gz
cd boost_1_81_0

默认安装

sudo ./bootstrap.sh 

安装boost

sudo ./b2 install

安装boost.build

cd ./tools/build
sudo ./bootstrap.sh
sudo ./b2 install
ldconfig

验证

1、程序thread.cpp

#include <boost/thread.hpp> 
#include <iostream> 

void wait(int seconds) 
{ 
    //POSIX(Portable Operating System Interface for Computing Systems)是由IEEE和ISO/IEC开发的一套标准
    //Portable :便携机; (尤指)手提电脑,便携式电视机
    boost::this_thread::sleep(boost::posix_time::seconds(seconds)); 
} 
//mutex :互斥锁
boost::mutex mutex; 

void thread() 
{ 
    for (int i = 0; i < 5; ++i) 
    { 
        wait(1); 
        mutex.lock(); 
        std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl; 
        mutex.unlock(); 
    } 
} 

int main(void) 
{ 
    boost::thread t1(thread); 
    boost::thread t2(thread); 
    t1.join(); 
    t2.join(); 
	return EXIT_SUCCESS;
} 

2、编译执行
为了链接POSIX thread库,可以采用两种方法:
直接在链接时,采用-lpthread
在编译和链接时都加上 -pthread
那么两者的区别是什么呢?
编译选项中指定 -pthread 会附加一个宏定义 -D_REENTRANT,该宏会导致 libc 头文件选择那些thread-safe的实现;链接选项中指定 -pthread 则同 -lpthread 一样,只表示链接 POSIX thread 库。由于 libc 用于适应 thread-safe 的宏定义可能变化,因此在编译和链接时都使用 -pthread 选项而不是传统的 -lpthread 能够保持向后兼容,并提高命令行的一致性。

[root@hackett boost]#  g++ thread.cpp -o thread.out -lboost_thread -pthread
[root@hackett boost]# ./thread
Thread 7f520774c700: 0
Thread 7f5206f4b700: 0
Thread 7f5206f4b700: 1
Thread 7f520774c700: 1
Thread 7f5206f4b700: 2
Thread 7f520774c700: 2
Thread 7f520774c700: 3
Thread 7f5206f4b700: 3
Thread 7f5206f4b700: 4
Thread 7f520774c700: 4

出自并修改:https://zhuanlan.zhihu.com/p/473413250

boost源码:https://boostorg.jfrog.io/artifactory/main/release/1.81.0/source/

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值