C++11 并发与多线程(二、线程创建,启动,结束)

一、线程运行的开始和结束

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

1. 创建线程

  1. join()函数 阻塞主线程,等待子线程执行完毕,然后子线程和主线程汇合,继续执行主线程
    std::thread obj(MyPrint);	//创建线程,线程入口函数MyPrint(),;线程开始执行
    obj.join();	//主线程阻塞,等待子线程执行完毕,join()执行完毕,主线程就继续往下执行
    
  2. detach()函数 线程分离,主线程不和子线程汇合,独立执行
    std::thread obj(MyPrint);	//创建线程,线程入口函数MyPrint(),;线程开始执行
    obj.detach();	//一旦detach(),主线程和子线程失去关联,此时子线程就会驻留在后台运行(这个子线程就相当于被C++运行时库接管,当子线程执行完成,由运行时库负责清理该线程的相关资源(守护线程))
    //一旦detach() 就不能再有join()了
    
  3. joinable()函数 判断是否可以成功使用 join() 或者 detach()函数(返回值为true表示可以使用join()或者detach() ; 返回false 表示不能join() 或者 detach() )
    std::thread obj(MyPrint);	//创建线程,线程入口函数MyPrint(),;线程开始执行
    if(obj.joinable())
    {
    	//可以join() 或者 detach()
    }
    else
    {
    	//不能再join() 或者 再 detach()
    }	
    

二、其他创建线程的手法

1. 用类对象作为可调用对象

		// MultiThread.cpp : 定义控制台应用程序的入口点。
	//
	
	#include "stdafx.h"
	#include <iostream>
	#include <thread>
	
	using namespace std;
	
	class Test
	{
	private:
		int m_i;
	public:
		Test(int i) :m_i(i) {
			cout << "构造函数被执行" << endl;
		}
		Test(const Test &test) :m_i(test.m_i) {
			cout << "拷贝构造函数被执行" << endl;
		}
		void operator()()	//仿函数
		{
			cout << "线程开始了:" << m_i  << endl;
			//.....
			cout << "线程结束了:" << m_i << endl;
			cout << "线程结束了:" << m_i << endl;
			cout << "线程结束了:" << m_i << endl;
		}
	};
	int main()
	{
		int i = 6;
		Test test(i);
		thread obj(test);	//会调用拷贝构造函数
		obj.detach();
	
		cout << "I Love China" << endl;
		system("pause");
	    return 0;
	}

2. 用lambda表达式

	int main()
	{
		auto myLambda = []() {		//当不带参数的时候 ()可以省略
			cout << "线程开始了:"  << endl;
			//.....
			cout << "线程结束了:"  << endl;
		};
		thread obj(myLambda);
		obj.join();
	
		cout << "I Love China" << endl;
		system("pause");
	    return 0;
	}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值