c++11多线程入门实例

#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;
}


c++11多线程入门实例_第1张图片


6个线程并发输出,第二个到第六个线程脱离了主进程,调用了t.detach();   主进程等待第一个线程,调用了t1.join();     t1.get_id()获得该线程id;

感觉和在linux下面的多线程好像,pthread_create()创建线程,pthread_join()等待线程,pthread_detach脱离主线程,pthread_self()获得该线程的id;具体用法看man手册;

你可能感兴趣的:(c++11多线程入门实例)