1、下载解压boost包
2、运行boost目录下启动安装脚本:
./bootstrap.sh --with-libraries=all --with-toolset=gcc
说明:--with-libraries指定需要编译的库,all表示编译所有boost库;--with-toolset指定编译器
没有报错则安装正常
3、编译
./b2 toolset=gcc
4、安装
./b2 install --prefix=/usr
说明:--prefix指定boost安装路径,/usr表示boost安装到系统头文件和库路径,可以省略环境变量
5、最后运行ldconfig命令
6、测试
#include <boost/thread/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream>
#include <cstdlib>
using namespace std;
//using namespace boost; //为什么此处声明了会导致system编译报错
bool isRuning = true;
int cnt = 0;
boost::mutex mtx_cnt;
void thread_proc1()
{
while( isRuning )
{
mtx_cnt.lock();
std::cout << "thread1 cnt: " << ++cnt << std::endl;
mtx_cnt.unlock();
boost::this_thread::sleep( boost::posix_time::milliseconds( 500 ) );
//sleep( 2 );
}
std::cout << "thread1 end" << std::endl;
}
void thread_proc2()
{
while( isRuning )
{
mtx_cnt.lock();
std::cout << "thread2 cnt: " << ++cnt << std::endl;
mtx_cnt.unlock();
boost::this_thread::sleep( boost::posix_time::milliseconds( 500 ) );
//sleep( 2 );
}
std::cout << "thread2 end" << std::endl;
}
int main( int argc, char* argv[] )
{
std::cout << "start" << std::endl;
boost::thread thread1( &thread_proc1 );
boost::thread thread2( &thread_proc2 );
system( "read" );
isRuning = false;
thread1.join();
thread2.join();
std::cout << "exit" << std::endl;
return 0;
}
编译:g++ main.cpp -o main -lboost_thread
./main 运行正常