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




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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值