From C++ Boost Thread 编程指南
http://www.cnblogs.com/chengmin/archive/2011/12/29/2306416.html
1.Demo function
(1)使用thread创建一个线程,线程函数没有参数,在主线程中调用join()函数等待子线程结束;
(2)创建两个线程,线程函数有参数,通过bind向子线程传入一个参数,在线程函数中使用Scope Lock模式对互斥资源(std::cout)加锁,在主线程中分别等待两个子线程的结束;
(3)使用thread_group创建一组线程,通过bind向子线程传入多个参数,在主线程中调用join_all()函数等待所有子线程的结束。
2.Demo Code
boost::mutex io_mutex;
//Test thread
void Thread_func()
{
cout << "Hello , I'm a thread..." << endl;
}
void Test_Thread()
{
boost::thread thrd(&Thread_func);
thrd.join();
}
//Test bind
void Fun(int id)
{
for (int i = 0; i < 5; ++i)
{//Scope Lock model
boost::mutex::scoped_lock lock(io_mutex);
cout << id << ": " << i << std::endl;
}
}
void Test_MutextBind()
{
boost::thread thrd1(boost::bind(&Fun, 1));
boost::thread thrd2(boost::bind(&Fun, 2));
thrd1.join();
thrd2.join();
}
int a[10];
int b[10];
//Test thread_group
void runChild(const int n,const int m)
{
a[n] = n*n;
b[n] = -m;
Sleep(1000);
boost::mutex::scoped_lock lock(io_mutex);
// cout 为共享资源 需加锁
cout << "I'm the " << n << "st child thread" << endl;
}
void TestThreadGroup()
{
boost::thread_group threads;
int num = 5;
cout << "I'm main thread, i want to yield " << num << " child threads" << endl;
for(int i = 0; i < num; i++)
{
threads.create_thread(boost::bind(&runChild, i,i*i));
}
cout << "I'm main thread, i'm waiting for the exit of all child threads!" << endl;
threads.join_all();
cout << "Calculate result of runChild ..." << endl;
for(int i = 0; i< num; i++)
{
cout << a[i] << ":" << b[i] << endl;
}
}
3.The Result