感受boost库的强大,其多线程真是简单好用,下面用一个简单的例子学习boost的多线程用法。
#include <boost/thread.hpp>
#include <iostream>
using namespace std;
boost::mutex mutex ;
void wait(int seconds)
{
boost::this_thread::sleep(boost::posix_time::seconds(seconds)) ;
}
int i ;
void thread()
{
for (i = 0 ; i < 5 ; i++)
{
// wait(1) ;
boost::lock_guard<boost::mutex> lock(mutex) ;
cout<<i<<"\t" ;
cout<<"Thread "<<boost::this_thread::get_id()<<":"<<endl ;
}
}
int main()
{
boost::thread t1(thread) ;
boost::thread t2(thread) ;
t1.join() ;
t2.join() ;
}
运行结果: