C++简单的线程创建及使用

本文介绍C++中如何通过标准库创建并使用线程,包括线程函数定义与调用,以及如何确保线程执行完毕。通过示例代码展示了两个并发线程的工作流程。

C++最简单的线程创建及使用

头文件:

#include<thread>

关键步骤:

  • thread mythread (线程函数, 参数1, 参数2…参数n);
  • mythread.join();

上实例代码

#include<iostream>
#include<thread>
using namespace std;

// 线程1函数
void aaa(int a, int b)
{
	cout << "111" << a << endl;
	cout << "1111" << a << endl;
	cout << "11111" << a << endl;
	cout << "111111" << a << endl;

}

// 线程2函数
void bbb(int a, int b)
{
	cout << "222" << a << endl;
	cout << "2222" << a << endl;
	cout << "22222" << a << endl;
	cout << "222222" << a << endl;

}
int main(int argc, char* argv[])
{
	thread mythread(aaa,55,6);    // 创建线程1
	thread mythread2(bbb, 55, 6); // 创建线程2
	mythread.join();  // 主线程阻塞到这,等待 aaa() 执行完毕
	mythread2.join(); // 主线程阻塞到这,等待 bbb() 执行完毕
	return 0;
}

输出:
在这里插入图片描述
由输出可看出,线程1和线程2同时进行。

结束:

分享也是自己对问题再次加深理解的方式,可能不全面,但绝对有用,后面将不断完善~

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

All In !!!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值