1.初识多线程
#include<thread>
using namespace std;
int main()
{
thread t(fun);
//t.detach; 子线程由C++运行时库接管,主线程和进程可能先于次线程先退出,导致次线程结果打印不到屏幕
if(t.joinable){
t.join;//主线程等待该子线程运行结束
}
return 0;
}
2.线程接受函数对象
#include<thread>
using namespace std;
//无参函数对象
class TA{
public:
void operator()(){
cout << "hello" << endl;
}
};
int main()
{
TA ta;
thread t(ta);
if(t.joinable){
t.join;//主线程等待该子线程运行结束
}
return 0;
}
#include<thread>
using namespace std;
//有参函数对象
class TA{
public:
int m_i;
TA(int& i) : m_i(i){}
void operator()(){
cout << m_i << endl;
}
};
int main()
{
int i=1;
TA ta(i);
thread t(ta);//调用TA的拷贝构造函数
if(t.joinable){
t.join;//主线程等待该子线程运行结束
}
return 0;
}
3.线程接受lambda表达式
auto fun1 = []{ cout << "hello" << endl;};
thread t(fun1);
4.线程接受带参函数
void myprint(const int& i, char* buf){
cout << i << endl;
cout << buf << endl;
}
int main(){
int i=1;
int& m_i=i;
char* buf = "hello";
thread t(myprint, i, buf);//虽然myprint接受的是引用,但是因为这里没有使用std::ref传参,myprint处理的还是只是i的拷贝
t.join();
return 0;
}