互斥锁(互斥量)

说明

  • mutex是独占式的互斥锁。timed_mutex增加了超时功能。
  • 成员函数:lock()用于锁定,try_lock()为非阻塞版本的锁定,unlock()用于解锁。timed_lock()只属于timed_mutex,它可以等待一定的时间,等待的时间可以是一个时间段,也可以是指定的时间。
  • 使用方法:使用mutex必须配合try-catch块以保证解锁互斥量,eg:

使用

#include "boost\thread.hpp"

int main()
{
    boost::mutex mu;
    try
    {
        mu.lock();
        cout << "Need to be protected" << endl; //io流是个共享资源,多线程内使用的话需要同步
        mu.unlock();
    }
    catch (...)
    {
        mu.unlock();
    }

    return 0;
}

mutex还提供了一系列的RAII型的互斥锁,用于取消麻烦的try-catch块,它会在构造的时候锁定互斥量,析构时自动解锁,eg:

#include "boost\thread.hpp"

int main()
{
    boost::mutex mu;
    boost::mutex::scoped_lock lock(mu);
    cout << "Need to be protected" << endl; //io流是个共享资源,多线程内使用的话需要同步

    return 0;
}

递归锁

说明

recursive_mutex是递归锁,可以多次锁定,相应的也要多次解锁。recursive_timed_mutex增加了超时功能。递归锁的使用接口跟互斥锁基本相同。

读写锁

说明

  • shared_mutex是读写锁,提供了multiple-reader / single-writer功能。
  • 读取锁定时我们使用shared_lock<shared_mutex>对象,写入锁定时我们使用unique_lock<shared_mutex>对象:

使用

boost::shared_mutex rw_mu;

    //read thread
    {
        boost::shared_lock<boost::shared_mutex> sl(rw_mu); //读锁定
        //......
    }
    
    //write thread
    {
        boost::unique_lock<boost::shared_mutex> ul(rw_mu); //写锁定
        //......
    }

条件变量

说明

  • condition_variable_any是条件变量,它用来在一个线程中等待某个事件的发生(满足某个条件),另一个线程会使条件成立。
  • 条件变量需要与一个互斥量配合使用。
    • condition_variable_any::wait()用来等待条件满足,
    • wait_for()用来等待条件满足直到超时,
    • wait_until()用来等待条件满足直到指定的时间,
    • condition_variable_any::notify_one() / notify_all()用来在条件满足的时候通知条件变量。
  • boost中的条件变量的使用方法与posix或windows下条件变量使用方法基本一致:

使用

#include "boost\thread.hpp"

boost::condition_variable_any g_cd;
boost::mutex g_mu;
bool g_bConditionFlag = false;

void Thread1Proc()
{
    boost::mutex::scoped_lock lock(g_mu);
    while (!g_bConditionFlag) //wait()方法返回也可能是线程的私自苏醒导致的,所以还需要判断条件
    {
        boost::this_thread::sleep(boost::posix_time::seconds(1));
        g_cd.wait(g_mu);
    }

    printf("thread1 exit\n");
}

int main()
{
    boost::thread t(Thread1Proc);
    t.detach();
    boost::this_thread::sleep(boost::posix_time::milliseconds(100));

    g_mu.lock();
    g_bConditionFlag = true;
    g_cd.notify_one();
    g_mu.unlock();

    printf("here\n");
    getchar();

    return 0;
}

barrier

说明

barrier称为护栏,它可以用来设置线程执行到barrier时必须等待,直到所有线程都达到这个点时才继续执行。