C++ 多线程练习1

学习资料

C++标准线程库之入门

1 代码

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

void fun1(int a)
{
	cout << "fun1(" << a << ")" << endl;
}

class demo
{
public:
	void operator()(int a)
	{
		cout << "demo(" << a << ")" << endl;
	}
};

int main()
{
	cout << "cpu线程数:" << thread::hardware_concurrency() << endl;
	thread t1(fun1, 3);
	cout << "t1.get_id()=" << t1.get_id() << endl << "t1.joinable()=" << t1.joinable() << endl;
	thread t2;
	cout << "t2.get_id()=" << t2.get_id() << endl << "t2.joinable()=" << t2.joinable() << endl;
	demo d;
	t2 = move(thread(d, 4));
	cout << "t2.get_id()=" << t2.get_id() << endl << "t2.joinable()=" << t2.joinable() << endl;
	system("pause");
	return 0;
}

2 运行结果及分析

第一次运行
分析主程序与fun1()函数可知,输出顺序为:
fun1函数的"fun1(" << a →主程序的 “t2.get_id()=" << t2.get_id() << endl → fun1函数的 “)” << endl; →主程序的 “t1.joinable()=” << t1.joinable() << endl;
说明主程序与线程t1在同时运行。同理,主程序与t2线程也是同时在运行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值