标签:blog http io os 使用 ar 文件 2014 sp
boost库是个准C++标准库,thread是其中重要的组成部分。它封装了不同操作系统的多线程编程,使得它具备了跨平台的能力。
首先是boost安装,从www.boost.org网站下下载最新的库,解压到本地目录下,重命名为boost
这里给出了安装脚本,该脚本采用静态链接多线程编译。 新建一个build_boost.sh的文件,将下述代码拷贝如文件内
#!/bin/bash machine=`uname -m | grep '64'` if [ a"$machine" == "a" ]; then bitlevel=32 else bitlevel=64 fi cd boost ./bootstrap.sh --prefix=./ ./bjam link=static threading=multi variant=release address-model=$bitlevel toolset=gcc runtime-link=static执行这个脚本即可
接下去是编程,新建一个example.cpp的文件,拷贝如下代码
<pre name="code" class="cpp">#include <boost/thread.hpp>
#include <iostream>
void task1() {
    std::cout << "This is task1!" << std::endl;
}
void task2() {
    std::cout << "this is task2!" << std::endl;
    sleep(5);
}
int main(int argc, char ** argv)
{
    using namespace boost;
    thread thread_1 = thread(task1);
    thread thread_2 = thread(task2);
    thread_2.join();
    thread_1.join();
    return 0;
}
编译需要如下语句,注意boost的位置,我的是和程序同一目录,所以使用./boost。当然需要提前安装g++(没有的话yum install g++)
g++ -I./boost -Iinclude -L./boost/stage/lib example.cpp -o example -lm -lboost_system -lboost_thread -lrt
由于是并行执行,其顺序是不确定的,如果看到先输出线程1也正常
在emeraldb中,使用boost的thread建了线程池,可以实现多用户连接和线程回收。
标签:blog http io os 使用 ar 文件 2014 sp
原文地址:http://blog.csdn.net/scjthree/article/details/39432963