c++lambda表达式和标准库线程学习

简单学习记录一下 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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值