简单学习记录一下 c++lambda表达式和c++标准库线程(window平台)
一、lambda表达式
#include <iostream>
using namespace std;
// [capture list] (parameter list) -> return type { function body }
int main()
{
auto add = [](int a, int b) { return (a + b); };
// 显示指定返回值类型
auto add2 = [](int a, int b) -> int { return (a + b); };
cout << add2(10, 20) << endl;
// 值捕获
int a = 20;
auto sub = [a](int b) { return a - b; };
cout << sub(10) << endl;
a = 30;
cout << sub(10) << endl;
// 引用捕获
int b = 10;
auto sub2 = [&b](int c) { return b - c; };
cout << sub2(5) << endl;
b = 20;
cout << sub2(5) << endl;
// 隐式捕获
int x = 10;
int y = 20;
auto func = [=, &y](int z) { return x + y + z; };
cout << func(30) << endl;
// 初始化捕获
int xx = 5;
auto func2 = [zz = xx + 10](int yy) { return zz + yy; };
cout << func2(15) << endl;
return 0;
}
二、线程库,创建线程
#include <iostream>
#include <stdio.h>
#include <thread>
#include <mutex>
#include <windows.h>
using namespace std;
void Thread1(int n)
{
char key = ' ';
cout << "Thread1 Started!\n" << endl;
while (1) {
key = getchar();
cout << "Thread1 Running!" << endl;
cout << key << endl;
}
}
void Thread2(void* args)
{
cout << "Thread2 Started!\n" << endl;
while (1) {
cout << "Thread2 Running!\n" << endl;
Sleep(100);
}
}
int main() {
thread th1(Thread1, 1);
thread th2(Thread2, nullptr);
thread th3([]() { cout << "lambda test thread " << endl; });
th1.join();
th2.join();
th3.join();
cout << "Hello World!\n" << endl;
}