最佳实践线程处理

时间:2017-10-22 15:08:55

标签: c++ multithreading c++11

目前我们正在课堂上进行多线程处理,并且我从老师和互联网的幻灯片中学习。

我们必须做一个计算(测量值的标准化),每个部分都是根据之前的一个而且我还必须使用互斥量进行一些特定的计算。

现在我为每个方法创建了一个额外的线程并加入它并为下一个线程做同样的事情,依此类推。

是否有更好的方法或最佳做法,现在它更像是尝试和错误(我不擅长c ++并学习它,但它是并行化的任务)?

我会将代码粘贴到这里,所以我可以理解我做了什么...对于凌乱的代码,它还没有完成,但是它正在工作:

#include <iostream>
#include <thread>
#include <vector>
#include <atomic>
#include <algorithm>
#include <math.h>


using namespace std;
//global variables because of quick and dirty...

vector<float> x = {-10.2, -8.0, 0.5, 5.9, 3.5, 22.7, 15.0, -1.8, -3.1, 7.7, 11.2, 7.9, -3.3,
                   -1.6, 15.3, 22.6, 3.6, 5.7, 2.0, -18.2, -27.5, 23.1, 18.1, 9.7, 25.8};
float mf;
float sf;
float oDN; //oDN= one divided by N
atomic<int> getXMf(0);
atomic<int> getXSf(0);
atomic<int> getXZ(0);

void calcMf() {
    for (getXMf; getXMf <= x.size(); getXMf++) {
        mf += oDN * x[getXMf];
    }
}
void calcSf() {
    for (getXSf; getXSf <= x.size(); getXSf++) {
        sf += oDN * (fabsf(x[getXSf] - mf));
    }
}
int main() {
    //initial args
    thread mythread
    vector<thread> worker1;
    vector<thread> worker2;
    vector<thread> worker3;
    float getSizeofX = x.size();
    oDN = 1 / getSizeofX;
    //
    //first worker doing calcMF and pushing to a vector
    for (int i = 0; i < mythread.hardware_concurrency(); ++i) {
        worker1.push_back(thread(&calcMf)
        );
    }
    //call first threads and join em;
    for (thread &ths: worker1) {
        ths.join();
    }

    //first worker doing calcMF and pushing to a vector
    for (int i = 0; i < mythread.hardware_concurrency(); ++i) {
        worker2.push_back(thread(&calcSf)
        );
    }
    //call second threads and join em;
    for (thread &ths: worker2) {
        ths.join();
    }

    cout << "mf: " << mf << endl;
    cout << "sf: " << sf << endl;

    return 0;
}

#include <algorithm>atomic<int> getXZ(0);尚未使用 编辑:修复了愚蠢的事情(线程[0])

0 个答案:

没有答案