本文参考: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;
}