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



發佈了63 篇原創文章 · 獲贊 9 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章