涉及:如何编译并执行c++程序、如何进行性能测试、使用objdump反汇编、volatile关键字
第五天:
1.编译并运行昨天复现的线程池代码
2.进行性能测试:对比线程池与直接创建线程的性能差异
写两个测试的函数:
main.cpp:
#include "ThreadPool.h"
#include <iostream>
#include <chrono>
void simple_task(int id) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << "Task " << id << " completed by thread "
<< std::this_thread::get_id() << std::endl;
}
int compute_task(int x) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
return x * x;
}
int main() {
std::cout << "--- ThreadPool Pool Test ---" << std::endl;
ThreadPool pool(4); // Create a thread pool with 4 threads
std::vector<std::future<void>> futures;
for(int i = 0; i < 10; ++i) {
futures.emplace_back(
pool.enqueue(simple_task, i)
);
}
std::cout << "-- Compute Task Test --" << std::endl;
std::vector<std::future<int>> results;
for(int i = 0; i < 5; ++i) {
results.emplace_back(
pool.enqueue(compute_task, i)
);
}
for(size_t i = 0; i < results.size(); ++i) {
std::cout << "Result of compute_task( " << i << " ) = " << results[i].get() << std::endl;
}
std::cout << "All tasks completed." << std::endl;
return 0;
}
1️⃣ get_id()
其功能是获取当前线程的ID,每个线程都有自己的独一无二的ID
补充说一点:thread构造函数的参数,如果使用引用传递,那么需要加std::ref
#include <functional> // 需要包含这个头文件
void modify_data(int& value, std::string& text) {
value *= 2;
text += " modified";
}
int main() {
int x = 100;
std::string msg = "test";
// 使用 std::ref 传递引用
std::thread t(modify_data, std::ref(x), std::ref(msg));
t.join();
std::cout << "x: " << x << ", msg: " << msg << std::endl;
// 输出: x: 200, msg: test modified
}
接着,编译:
g++ -std=c++20 -pthread main.cpp -o thread_pool_test
1️⃣g++
g++是GNU C++编译器,它是GCC(GNU Compiler Collection)的一部分
2️⃣-std=c++20
告诉编译器使用C++20标准来编译代码
3️⃣-pthread
表示链接POSIX线程库,用来链接多线程相关的库文件以及定义必要的预处理宏
在Linux系统上编译多线程程序时必须加上这个选项
4️⃣-o
main.cpp 源代码文件
-o thread_pool_test 指定输出文件名
-o直接生成最终的可执行文件
最终我们可以看到目录下生成了thread_pool_test.exe可执行文件
运行:
./thread_pool_test
结果:

注意到Task2的完成语句还没有输出完,Task0的完成语句已经抢先输出了
这是正常现象,因为输出完成语句不是原子操作,不同线程可能在不同步骤之间交错进行,导致输出混乱
另外,id为124881284875840的线程处理了多个任务

最低0.47元/天 解锁文章
992

被折叠的 条评论
为什么被折叠?



