您的位置:首页 > 编程语言 > C语言/C++

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

2016-04-27 23:44 218 查看

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 = 8
7016    n = 0
线程编号:6448  n = 14
线程编号:7844  n = 1
线程编号:8500  n = 13
请按任意键继续. . .


待续....
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: