C++ 教程 - 09 多线程处理

文章目录

thread标准库

  • C++ 11 后添加了新的标准线程库 std::thread 类,
  • 需引入头文件<thread>
  • 支持windows,linux平台(linux平台下需要导入<pthread.h>,编译时并链入libpthread.so),可以利用多核cpu,并行执行,但是python的多线程却不可以利用多核心;
  • 声明变量并创建线程对象,如 thread th1; 调用无参构造,生成一个空的线程对象;
  • thread th(callable, args),传入调用函数及参数;
    • callable,可为函数;
    • callable,可为可调用对象;
    • callable,可为lambda 表达式(无名函数)
    • th.join() 等待当前子线程执行结束;
  • std::this_thread::sleep_for(chrono::seconds(1)) 线程内部延迟1s;
  • std::this_thread::get_id();
  • std::thread::harware_concurrency() 获取cpu核心数, 一般num + 1 个线程;
  • g++编译时,指定 -std=c++11 或者更新的版本;
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;
}

pthread库

  • linux下使用pthread库创建子线程;
  • 需包含头文件<pthread.h>,且编译时链入libpthread.so动态库;
    • pthread_t 线程id类型;
    • pthread_create(&curThID, attr, funcName, void* args) 创建线程并执行,成功返回0,并将线程id存入curThID变量地址; attr线程对象的属性(可NULL); funcName为返回void* 且参数为void*的函数
    • 默认为守护线程,主线程结束时,不管子线程有没有结束,均都随主线程一起退出;
    • pthread_exit(NULL) ,在主线程中等待子线程执行结束;
    • pthread_attr_t 线程对象属性类型;
    • pthread_attr_init(&attr) 线程对象属性初始化;
    • pthread_attr_delete(attr) 线程对象属性删除;
    • pthread_join(thId, status) 连接线程,顺序执行;
    • pthread_detach() 分离线程;
cpp 复制代码
在这里插入代码片
相关推荐
ka2x9 分钟前
订单折扣金额分摊算法|代金券分摊|收银系统|积分分摊|分摊|精度问题|按比例分配|钱分摊|钱分配
java·c语言·c++·python·算法·spring·spring cloud
爱上电路设计4 小时前
有趣的算法
开发语言·c++·算法
窜天遁地大吗喽4 小时前
每日一题~ (判断是否是合法的出栈序列)
c++
yachihaoteng7 小时前
Studying-代码随想录训练营day27| 贪心算法理论基础、455.分发饼干、376.摆动序列、53.最大子序和
c++·算法·leetcode·贪心算法
逸群不凡7 小时前
C++|哈希应用->布隆过滤器
开发语言·数据结构·c++·算法·哈希算法
从后端到QT7 小时前
Qt 基础组件速学 鼠标和键盘事件
c++·qt
quaer8 小时前
使用引用返回类对象本身
开发语言·c++·算法
w_outlier8 小时前
gcc/g++的四步编译
linux·c++·gcc·g++
Navigator_Z8 小时前
C++ //练习 14.39 修改上一题的程序令其报告长度在1至9之间的单词有多少个、长度在10以上的单词又有多少个。
开发语言·c++·算法
一子二木生三火8 小时前
set的应用(C++)
开发语言·c++