demo
先来个最简单的demo,启动的线程是一个无返回值无参数的函数。
添加头文件#include <thread>
#include "stdafx.h"
#include <iostream>
#include <thread>
using namespace std;
void hello()
{
cout << "Hello world" << endl;
}
int main()
{
thread t(hello);
t.join();
getchar();
return 0;
}
thread t(hello);这个就启动线程了,t.join()是等待线程t 运行完。
分离线程
如果想运行一个线程和主线程无关的使两个线程同时运行,就可以使用分离线程。join()函数是等待线程,子线程和主线程并没有分开运行,而是等待子线程运行完,主线程再运行。
detach()函数就是可以分离线程。
#include "stdafx.h"
#include <iostream>
#include <thread>
using namespace std;
void hello()
{
cout <<"thread two" <<" Hello world" << endl;
}
int main()
{
thread t(hello);
//t.join();
t.detach();
cout << "thread one" << endl;
getchar();
return 0;
}
其中被分离的线程通常被称为守护线程。
传递参数给线程
其实就是在函数名后面跟上函数的参数。
#include "stdafx.h"
#include <iostream>
#include <thread>
#include <string>
using namespace std;
void hello()
{
cout <<"thread two" <<" Hello world" << endl;
}
void f(int i, string s)
{
cout << "i = " << i << ", string = " << s << endl;
}
int main()
{
thread t(f,3,"asdf");
t.join();
//t.detach();
cout << "thread one" << endl;
getchar();
return 0;
}