C++线程池学习 Day05

涉及:如何编译并执行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的线程处理了多个任务

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值