boost thread usage demo

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值