【c++】多线程大幅缩减时间

文章展示了如何在C++中使用多线程进行复杂运算,通过线程同步实现并行处理,以节约时间和提高性能。作者提供了代码片段,展示了如何在main函数中创建和管理多个线程以及检查线程完成情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

多线程在进行复杂运算时能够大量节约时间
提醒自己能够在多线程运算的时候一定要充分利用
在这里插入图片描述
能够省下2/3的时间
在这里插入图片描述
测试代码

#include<vector>
#include <iostream>
#include <thread>
using namespace cv;
using namespace std;
int result1 = 0 ;
bool thread_flag1 = false;
bool thread_flag2 = false;
bool thread_flag3 = false;
bool thread_flag4 = false;


void add_fn (int time)
{
    int result = 0;
    for (int i = 0 ;i < 10000000 ;i++)
    {
        result +=  i ;
    }  
    // cout << "the " << time  <<"time " << result <<endl;
    if (time == 1 ) thread_flag1 = true;
    else if (time == 2 ) thread_flag2 = true;
    else if (time == 3 ) thread_flag3 = true;
    else thread_flag4 = true;

    // return result ;
}
void check_thread()
{
    auto beforeTime = std::chrono::steady_clock::now();
    while(1)
    {
        if(thread_flag1&&thread_flag2&&thread_flag3&&thread_flag4)
        {
            auto afterTime = std::chrono::steady_clock::now();
            double duration_microsecond = std::chrono::duration<double, std::micro>(afterTime - beforeTime).count();
            cout << "threads take times"<< duration_microsecond <<"microsecond" <<endl;
            break;
        }
    
    }
    
}

int main()
{
    thread check(check_thread);
    check.detach();
    for (int i = 0;i < 4 ; i++)
    {
        std::thread t(add_fn , i);
        t.detach();
    }
    auto beforeTime = std::chrono::steady_clock::now();
    for (int i = 0;i < 4 ; i++)
    {
        add_fn(i);
    }
    auto afterTime = std::chrono::steady_clock::now();
    double duration_microsecond = std::chrono::duration<double, std::micro>(afterTime - beforeTime).count();
    cout << "all take times"<< duration_microsecond <<"microsecond" <<endl;
    
    while(1)
    {
        
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值