boost::thread多线程

1.thread库简介

thread库依赖chrono库。chrono库是C++11新加入的方便日期时间操作的标准库,thread库需要chrono库提供的时间概念来执行睡眠、等待操作,因此编译thread库需要先编译chrono库。
thread位于命名空间boost,包含于头文件中:

#define BOOST_THREAD_BERSION 4 //最新版本
#include 
using namespace boost;

在C++标准之外,thread库还提供了大量的扩展功能,但是出于对兼容性的考虑,这些功能包含在其他的头文件中:

#include 
#include 
#include 
#include 
#include 
#include 

2.A simple example

#include 
#include 

void hello()
{
      std::cout<<"Hello multi-thread!"<

这个例子中,main函数是一个线程,新建的线程用于输出“hello multi-thread!”。同时调用boost::thread::join()来等待线程执行结束。

3.互斥体

多线程程序要避免不同的线程同时访问共享区域。为了避免多个线程多共享区域的同时访问,产生了互斥体(mutex,mutual extension的缩写),一个互斥体一次只允许一个线程访问共享区。当一个线程想要访问共享区时,首先要锁住(lock)互斥体,互斥体一旦被锁住,其他线程想要再访问共享区,只能等到当前线程结束,解锁互斥体。

#include 
#include 
#include 
#include 

boost::mutex io_mutex;

void count(int id)
{
      for(int i = 0;i < 10; i++)
      {
            boost::mutex::scoped_lock lock(io_mutex);
            std::cout<

不明白怎么用boost::bind(),可以参考我的文章boost::bind函数绑定器一文。


多线程的内容太多了,待我慢慢来写。未完待续。

你可能感兴趣的:(boost::thread多线程)