linux多线程编程--对三层for循环的优化

本文探讨了如何对包含三层for循环的代码进行多线程优化,通过实验证明,在8个线程下运行时间为11秒。在4核8CPU的系统中,发现8个线程效率最高,再多的线程只会导致资源浪费。优化主要使用了pthread_create和pthread_join函数,因为线程间无数据冲突,若存在冲突则需引入锁机制。
摘要由CSDN通过智能技术生成

目标:将下面3层for循环的代码进行优化:

#include <iostream>
#include <vector>
#include <pthread.h>

using namespace std;

typedef vector< vector<long> > lvec;

long arr[1000][5000] = {};

long acculate(int, int);
lvec& forarr(lvec&, long, long);



int main()
{
    long sum(0);
    lvec ivec;
    ivec.resize(1000);
    
    for (long i=0; i<1000; ++i) {
        for (long j=0; j<5000; ++j)
            ivec[i].push_back(j);
    }
    cout << ivec[999][4999] << endl;
    
    for (long i=0; i<1000; ++i) {
        ivec = forarr(ivec, i, 0);
        pthread_t id;
        int ret = pthread_create(&id, 0, forarr, 0);
        if (!ret)
            cout << "failed to create thread!" << endl;
        ivec = forarr(ivec, i, 2500);
    }
                  
    cout << ivec[999][4
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值