cpp
复制代码
#include <iostream>
#include <string>
// C++11后引入的 线程 标准库 std::thread 类 std::this_thread
#include <thread>
#include <chrono> // 延迟时间
using namespace std;
// 定义类
class People {
public:
int age; // 实例 成员变量
string name;
People() {
cout << "走无参构造函数..." << endl;
this->age = 30;
}
People(const string& name, const int& age) {
cout << "走有参构造函数..." << endl;
this->name = name;
this->age = age;
}
virtual ~People() {
cout << "删除对象" << endl;
}
// 重载 函数调用()运算符,对象才可以调用
void operator()(int age) {
for (int i = 0; i < age; i++) {
cout << "param age:" + to_string(age) << endl; // to_string 将int转为字符串,字符串支持 + 连接
cout << "成员age:" << this->age << endl;
// 延迟1s
this_thread::sleep_for(chrono::seconds(1));
cout << this_thread::get_id() << endl;
}
}
};
struct book { // 定义结构体,同C语法一致,只不过C++中可以单独使用book类声明变量,而C中必须使用struct book 声明
char *title;
double price;
};
// 函数
void myFunc(book arr[], int arrLen) {
for (int i = 0; i < arrLen; i++) {
cout << "当前书籍:" << endl;
cout << arr[i].title << endl;
cout << arr[i].price << endl;
//std::this_thread 线程延迟1s
this_thread::sleep_for(chrono::seconds(1));
// 打印线程id
cout << "线程id:" << this_thread::get_id() << endl;
cout << "" << endl;
}
}
int main() {
// 创建空子线程
thread th1;
// 创建子线程,并传参 '调用函数'、参数
struct book arr[3]; // 数组分配内存,并创建结构体对象
// 对象的指针属性,必须动态分配内存
arr[0].title = new char(20);
arr[0].title = (char*)"三国演义"; // 为对象赋值
arr[0].price = 23.5;
arr[1].title = new char(20);
arr[1].title = (char*)"西游记";
arr[1].price = 30.5;
arr[2].title = new char(20);
arr[2].title = (char*)"水浒传";
arr[2].price = 28.5;
thread th2(myFunc, arr, 3);
// 创建子线程,并传参 lambda 表达式 (无名函数)
auto exp1 = [](const int& num) { cout <<"lambda:" << num << endl; }; // 必须有 ; 号
thread th3(exp1, 5);
// 创建子线程,并传入 '可调用对象'、参数
thread th4(People(), 20);
// 等待子线程结束
// th1.join(); // 空的子线程 不能.join()
th2.join();
th3.join();
th4.join();
return 0;
}