安装包安装
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/