C++多线程初级一:创建线程

本文参考:http://blog.csdn.net/jonathan321/article/details/52679471

以函数为参数创建线程:

 

// PolythreadDemo.cpp : 定义控制台应用程序的入口点。
//这里有一个观点,就是当使用某个函数的时候,再
//写上头文件,不用一开始就来、

#include "stdafx.h"

#include <iostream>
#include <thread>
#include <windows.h>


using namespace std;

void hello(){
	cout << "Hollo,Nima World!" << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	std::thread t(hello);
	t.join(); //只有上面两句话,和之前的预处理指令
	

	Sleep(3000); //定义在windows.h里面、
	return 0;
}

 

以函数对象为参数创建线程

 

// PolythreadDemo.cpp : 定义控制台应用程序的入口点。
//这里有一个观点,就是当使用某个函数的时候,再
//写上头文件,不用一开始就来、

#include "stdafx.h"

#include <iostream>
#include <thread>
#include <windows.h>


using namespace std;

void hello(){
	cout << "Hollo,Nima World!" << endl;
}

class Hello
{
public:
	Hello(){} //构造函数、
	void operator()()const
	{
		std::cout << "Hello,World!" << std::endl;
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	Hello h;
	std::thread t1((h)); //原文中只有一个括号,没看懂,放两个括号就清楚了
	t1.join(); //只有上面两句话,和之前的预处理指令
	

	Sleep(3000); //定义在windows.h里面、
	return 0;
}




以类方法作为参数创建线程:

// PolythreadDemo.cpp : 定义控制台应用程序的入口点。
//这里有一个观点,就是当使用某个函数的时候,再
//写上头文件,不用一开始就来、

#include "stdafx.h"

#include <iostream>
#include <thread>
#include <windows.h>

#include <string>

using namespace std;

void hello(){
	cout << "Hollo,Nima World!" << endl;
}

class Hello
{
public:
	Hello(){} //构造函数、
	//注意函数名必须唯一才能做多线程、
	void hello1(){
		cout << "Hollo,Nima World!" << endl;
	}
	void hello2(std::string text){ //string 要加String头文件
		cout << "Hollo,Nima World!" << text << endl; 
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	Hello h;
	std::thread t1(&Hello::hello1,&h); 
	std::thread t2(&Hello::hello2,&h,"Shawn");
	t1.join(); 
	t2.join();
	

	Sleep(3000); //定义在windows.h里面、
	return 0;
}



 

以lambda对象作为参数创建线程

// PolythreadDemo.cpp : 定义控制台应用程序的入口点。
//这里有一个观点,就是当使用某个函数的时候,再
//写上头文件,不用一开始就来、

#include "stdafx.h"

#include <iostream>
#include <thread>
#include <windows.h>

#include <string>

using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
	std::thread t([](std::string text){
		std::cout << "Hello,caodan World!" << text << std::endl;
	}, "Shawn");
	t.join();

	Sleep(3000); //定义在windows.h里面、
	return 0;
}


 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值