并发,线程,进程

一个是实力的体现,一个是商用的必须需求。
以往:
windows: CreatThread(),_beginthred(),_beginthredexe()
Linux: pthread_create() 创建线程

临界区,互斥量。以往多线程代码不能跨平台。
从C++11开始,C++语言本身增加可移植性。

整个进程是否执行完毕的标志是主线程是否执行完毕。此时,如果主线程执行完毕,但是其他子线程还没有执行完毕,那么,这些子线程也会被操作系统强行终止。

1.包含头文件:

#include<thread>

2.创建一个线程函数

void myprint()
{
	cout << "线程开始运行" << endl;
	//...
	//...
	//...
	cout << "线程执行完毕" << endl;
}

3.main中开始写代码

std::thread mythread(myprint);
mythread.join();//阻塞主线程,让主线程等待

传统多线程:等待子线程执行完毕,然后自己最后在退出。
detach():主线程可以不等子线程执行完毕,就结束程序。此时子线程跑到系统的后台运行,相当于被C++运行时库接管,当这个子线程执行完成后,由运行时库负责清理相关资源。
一旦detach(),就不能join(),否则会出现异常。

void myprint()
{
	cout << "线程开始运行" << endl;
	cout << "1" << endl;
	cout << "2" << endl;
	cout << "3" << endl;
	cout << "4" << endl;
	cout << "5" << endl;
	cout << "线程执行完毕" << endl;
}
std::thread mythread(myprint);
	mythread.detach();//一起打印,但是主线程完毕后,就结束程序
	cout << "hello world" << endl;

在这里插入图片描述

joinable():判断能不能使用join或detach。

	std::thread mythread(myprint);
	if(mythread.joinable())
		mythread.join();
	else 
		mythread.detach();
	cout << "hello world" << endl;

在这里插入图片描述

线程参数:当线程引入参数时,是以复制的形式,

class T {
	int i;
public:
	T(int j):i(j)
	{
		cout << "构造函数执行" << endl;
	}
	T(const T &j) 
	{
		i = j.i;
		cout << "拷贝构造函数执行" << endl;
	}
	void operator()()
	{
		cout << "i=" << i << endl;
	}
	~T()
	{
		cout << "析构函数执行" << endl;
	}
};

在这里插入图片描述

auto thread = [] {
		cout << "线程开始执行" << endl;
	};
	std::thread mythread(thread);
	if(mythread.joinable())
		mythread.join();
	else 
		mythread.detach();
	cout << "hello world" << endl;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值