首页 > 代码库 > boost thread使用
boost thread使用
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
代码是网上找来的,用thread(func)构造函数新建一个线程,join是挂起一个进程直到它执行完。显然两个线程是并行执行的,所以执行thread_2时先等待5秒,但同时也会执行thread_1,最终效果如下
由于是并行执行,其顺序是不确定的,如果看到先输出线程1也正常
在emeraldb中,使用boost的thread建了线程池,可以实现多用户连接和线程回收。
boost thread使用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。