boost--线程同步

时间:2022-06-11 03:14:25

1、互斥锁(互斥量)

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 ;
}

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 ;
}

使用实例:以下定义了一个支持原子前++的计数器atom_increase:

#include "boost\thread.hpp"

template<typename T>
class atom_increase
{
public:
atom_increase(T x = ): n(x){} //转换构造函数,实现T类型到atom_increase类型的隐式转换 T operator++() //重载前++运算符
{
boost::mutex::scoped_lock lock(mu);
return ++n;
} operator T() { return n; } //类型转换函数,实现atom_increase类型到T类型的隐式转换 private:
T n;
boost::mutex mu;
}; int main()
{
atom_increase<int> n = ; //隐式转换:int -> atom_increase
++n; //原子前++
int i = + n; //隐式转换:atom_increase ->int return ;
}

2、递归锁

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

3、读写锁

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); //写锁定
//......
}

4、条件变量

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)
{
boost::this_thread::sleep(boost::posix_time::seconds());
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()); g_mu.lock();
g_bConditionFlag = true;
g_cd.notify_one();
g_mu.unlock(); printf("here\n");
getchar(); return ;
}

 5、barrier

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

 6、C++11中的线程操作

c++11也提供了创建线程和线程同步的方法,c++11里的mutex,与boost里的mutex用法类似:

#include <iostream>       // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::lock std::mutex foo, bar; void task_a()
{
// foo.lock();
// bar.lock();
std::lock(foo, bar);
std::cout << "task a\n"; foo.unlock();
bar.unlock();
} void task_b()
{
// bar.lock();
// foo.lock();
std::lock(bar, foo);
std::cout << "task b\n";
bar.unlock();
foo.unlock();
} int main()
{
std::thread th1(task_a);
std::thread th2(task_b);
// th1.detach();
// th2.detach();
th1.join();
th2.join(); return ;
}

创建线程的时候需要注意三点:

①、如果使用函数对象作为thread的参数的话,直接传入临时对象会出错,可以定义一个对象传入或者使用lambda表达式:

class CTask
{
public:
void operator()()
{
int a = ;
}
}; //std::thread th1(CTask()); //直接传入临时对象会出错
CTask task;
std::thread th1(task);
th1.join();

②、传递给线程函数的参数是先保存在于一个中转站中,当函数执行的时候再传给函数的形参,而这个时候传递的参数指向的值很有可能已经失效,所以,对于线程函数传递的参数应该与形参类型相同,而不是再进行转换。

③、如果线程函数的参数是引用的话传入时还需要结合ref来使用。

    void task(int& a, string str)
{ } int iNum = ;
char* pStr = new char[];
strcpy(pStr, "test");
//std::thread th(task, 5, std::ref(iNum), pStr); //不应该直接传入pStr
std::thread th(task, std::ref(iNum), string(pStr)); //应该传入对应类型
delete[] pStr;
th.join();

c++中的lock_guard、unique_lock也是RAII型的互斥锁,类似boost的scoped_lock,使用示例:

    std::lock_guard<std::mutex> _lock(m_mutex);
g_num++;

unique_lock在lock_guard的基础上增加了加锁和解锁的接口方法,对比下面的fun1和fun2,二者效果相同,通过代码可以看出二者区别:

std::mutex g_mu;

void fun1()
{
{
std::lock_guard<std::mutex> guard(g_mu);
//do something 1
} //do something 2 {
std::lock_guard<std::mutex> guard(g_mu);
// do something 3
}
} void fun2()
{
std::unique_lock<std::mutex> guard(g_mu);
//do something 1
guard.unlock(); //do something 2 guard.lock();
// do something 3
}

unique_lock可以配合条件变量来使用,而lock_guard不能,因为lock_guard没有加锁和解锁的接口方法。另外,unique_lock和lock_guard都不能复制,unique_lock可以移动,lock_guard不能移动。c++11中的条件变量condition_variable与boost的使用类似,其接口方法有wait()、notify_one()等。