-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path多线程在函数和lambda算子中.cpp
58 lines (46 loc) · 1.71 KB
/
多线程在函数和lambda算子中.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
* @Author: your name
* @Date: 2020-04-10 17:28:24
* @LastEditTime: 2020-04-11 17:46:22
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: /C++课程学习记录/thread多线程/intro.cpp
*/
#include <iostream>
#include <thread> // 线程库 编译时要加 -pthread 参数
#include <chrono> // hrono 时钟库,以各种精度跟踪时间的类型的灵活汇集
using namespace std::chrono;
using namespace std;
using ull = unsigned long long;
ull OddSum = 0;
ull EvenSum = 0;
void findEven(ull start, ull end) {
for (ull i = start; i <= end; ++i)
if ((i & 1) == 0)
EvenSum += i;
}
void findOdd(ull start, ull end) {
for (ull i = start; i <= end; ++i)
if ((i & 1) == 1)
OddSum += i;
}
int main() {
ull start = 0, end = 1900000000;
// 引入线程t1, t2
auto startTime = high_resolution_clock::now(); // 高分辨率时钟
// findOdd(start, end); // 寻找奇数
// findEven(start, end); // 寻找偶数
// std::thread t1(findOdd, start, end);
// 或者将t1线程的 定义语句和函数 利用lambda算子合并
std::thread t1([](int start, int end){int i = 0; for(int i = start; i < end; i ++) { if(i & 1 == 1) OddSum += 1; }}, start, end);
t1.join();
std::thread t2(findEven, start, end);
t2.join();
auto stopTime = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(stopTime - startTime);
// 1seconds = 1,000milliseconds 毫秒 = 1,000,000microseconds 微秒 = 1,000,000,000nanosecond 纳秒
cout << "EvenSum = " << EvenSum << endl;
cout << "OddSum = " << OddSum << endl;
printf("%.2fs\n", float(duration.count()/1000.0));
return 0;
}