直接总结多线程写法:
1.直接启动函数:
#include <iostream>
#include <windows.h>
#include <thread>
void fun1(){
for(int i = 0; i < 3; i++){
std::cout << "fun1" << std::endl;
Sleep(500);
}
}
void fun2(){
for(int i = 0; i < 3; i++){
std::cout << "fun2" << std::endl;
Sleep(500);
}
}
int main(){
std::thread mythread1(fun1);
std::thread mythread2(fun2);
mythread1.join();
mythread2.join();
return 0;
}
运行结果:
2.lambd表达式:
#include <iostream>
#include <windows.h>
#include <thread>
void fun1(){
for(int i = 0; i < 3; i++){
std::cout << "fun1" << std::endl;
Sleep(500);
}
}
int main(){
std::thread mythread1([](){
for(int i = 0; i < 3; i++){
std::cout << "lambd()" << std::endl;
Sleep(500);
}
});
fun1();
mythread1.join();
return 0;
}
运行结果:
3.类启动, 重写operator():
#include <iostream>
#include <windows.h>
#include <thread>
void fun1(){
for(int i = 0; i < 3; i++){
std::cout << "fun1" << std::endl;
Sleep(500);
}
}
class A{
public:
void operator()(){
for(int i = 0; i < 3; i++){
std::cout << "operator()" << std::endl;
Sleep(500);
}
}
};
int main(){
A a;
std::thread mythread1(a);
fun1();
mythread1.join();
return 0;
}
运行结果:
4.类成员函数指针做线程函数:
#include <iostream>
#include <windows.h>
#include <thread>
void fun1(){
for(int i = 0; i < 3; i++){
std::cout << "fun1" << std::endl;
Sleep(500);
}
}
class B{
public:
void thread_fun(int num){
for(int i = 0; i < num; i++){
std::cout << "thread_fun()" << std::endl;
Sleep(500);
}
}
};
int main(){
B b;
std::thread mythread1(&B::thread_fun,&b, 4);
fun1();
mythread1.join();
return 0;
}
运行结果: