巩固C++(二)----多线程编程

来源:互联网 发布:制作vr的软件 编辑:程序博客网 时间:2024/05/22 16:49

1 C++11 多线程编程

先来一个例子:
#include<iostream>#include<vector>#include<stdlib.h>#include<thread>#include<windows.h>using std::cout;using std::endl;using namespace std::this_thread;using std::thread;using std::vector;void print(int n){//打印的顺序是一定的,且完整度也会受到影响cout << "线程编号:" << get_id() << "\tn = " << n << endl;}int main(){//返回硬件线程上下文的估计的静态方法,自己定义多线程时,最好是其整数倍int thdNo = thread::hardware_concurrency();cout << "My Thread is " << thdNo << endl;vector<thread *> vec;for (int i = 0; i < thdNo * 2 - 1; i++){//建立多线程的过程,其实线程也是有优先级的vec.push_back(new thread(print, i));}for (auto it : vec){//加入多线程it->join();}system("pause");return 0;}

运行结果:
My Thread is 8线程编号:线程编号:5336        n = 4线程编号:7172  n = 9线程编号:8736  n = 6线程编号:7808  n = 10线程编号:8756  n = 3线程编号:7272  n = 7线程编号:5348  n = 11线程编号:6112  n = 2线程编号:8568  n = 5线程编号:8200  n = 12线程编号:6860  n = 87016    n = 0线程编号:6448  n = 14线程编号:7844  n = 1线程编号:8500  n = 13请按任意键继续. . .


待续....

0 0
原创粉丝点击