c++11多執行緒入門例項

readyao發表於2015-12-09
#include <iostream>
#include <thread>
#include <chrono>
#include <random>
#include <exception>

using namespace std;


void doSomething(int num, char c)
{
	try{
		default_random_engine dre(42 * c);
		uniform_int_distribution<int> id(10, 100);
		for (int i = 0; i < num; ++i){
			this_thread::sleep_for(chrono::milliseconds(id(dre)));
			cout.put(c).flush();
		}
	}
	catch (const exception & e){
		cerr << "exception is :thread id is " << this_thread::get_id() << ", " << e.what() << endl;
	}

}


int main()
{
	try{
		thread t1(doSomething, 5, '.');
		cout << "start the t1 thread " << t1.get_id() << endl;
		for (int i = 0; i < 5; ++i){
			thread t(doSomething, 10, 'a' + i);
			cout << "detach start the thread " << t.get_id() << endl;
			t.detach();
		}

		cin.get();

		cout << "join the t1 thread " << t1.get_id() << endl;
		t1.join();
	}
	catch (const exception &e){
		cerr << "exception is " << e.what() << endl;
	}



	system("pause");
	return 0;
}




6個執行緒併發輸出,第二個到第六個執行緒脫離了主程式,呼叫了t.detach();   主程式等待第一個執行緒,呼叫了t1.join();     t1.get_id()獲得該執行緒id;

感覺和在linux下面的多執行緒好像,pthread_create()建立執行緒,pthread_join()等待執行緒,pthread_detach脫離主執行緒,pthread_self()獲得該執行緒的id;具體用法看man手冊;

相關文章