目录
1--基于 thread 创建线程
1-1--使用函数对象创建线程
# include <iostream>
# include <thread>
void myprint(){
int i = 100;
while(i > 0){
std::cout << "thread print" << std::endl;
i--;
}
}
int main(){
// 创建子线程对象
std::thread thread1(myprint);
int i = 100;
while(i > 0){
std::cout << "main print" << std::endl;
i--;
}
thread1.join(); // 阻塞主线程,主线程需等待子线程执行完毕
return 0;
}
1-2--使用类对象创建线程
# include <iostream>
# include <thread>
class myclass{
public:
// 函数名必须为 operator, 且不能携带参数
void operator()(){
int i = 100;
while(i > 0){
std::cout << "thread print" << std::endl;
i--;
}
}
};
int main(){
// 创建子线程对象
myclass class1;
std::thread thread1(class1);
int i = 100;
while(i > 0){
std::cout << "main print" << std::endl;
i--;
}
thread1.join(); // 阻塞主线程,主线程需等待子线程执行完毕
return 0;
}
// Error bug code
# include <iostream>
# include <thread>
class myclass{
public:
myclass(int &index):my_i(index){}; // 用引用传递的 i 初始化 my_i
// 函数名必须为 operator, 且不能携带参数
void operator()(){
int i = 100;
while(i > 0){
std::cout << "thread print" << std::endl;
i--;
}
}
private:
int my_i;
};
int main(){
// 创建子线程对象
int index = 1;
myclass class1(index);
std::thread thread1(class1);
int i = 100;
while(i > 0){
std::cout << "main print" << std::endl;
i--;
}
thread1.detach(); // 阻塞主线程,主线程需等待子线程执行完毕
return 0;
}
1-3--使用lambda表达式创建线程
# include <iostream>
# include <thread>
int main(){
auto lamthread = [](){
int i = 100;
while(i > 0){
std::cout << "thread print" << std::endl;
i--;
}
};
std::thread thread1(lamthread);
thread1.detach(); // 主线程和子线程分离
int j = 100;
while(j > 0){
std::cout << "main print" << std::endl;
j--;
}
return 0;
}