使用向量导致运行时错误的多线程

时间:2016-02-15 05:48:28

标签: c++ multithreading vector

我正在进行一项任务,我需要计算1到1千万的素数频率。我们要通过获取变量U(1000万)并将其划分为N个部分并使用多个线程计算素数的频率来实现这一点,我们必须尝试使用​​不同的N值,并观察我们的过程滴答和时间。计算。我认为最好的方法是使用矢量,教授推荐它。然而,当我运行我的代码时,我得到两个运行时错误,第一个是"矢量下标超出范围"第二个"标准C ++库超出范围&& 0" 。我检查一下,看看我是否在某些地方的界限范围内,但似乎我没有。下面是代码。谢谢你看一看,非常感谢任何反馈

#include <iostream>
#include <thread>
#include <vector>
#include<algorithm>
#define MILLION 1000000
using namespace std;
using std::for_each;
void frequencyOfPrimes(long long upper, long long lower, long long* freq)
{
    long long i, j;
    *freq = upper - 1;
    for (i = lower; i <= upper; ++i)
        for (j = (long long)sqrt(i); j>1; --j)
            if (i%j == 0) { --(*freq); break; }
    return;
}

int main(int argc, char* argv[])
{

    clock_t ticks = clock();
    long long N = 5;
    long long U = 10*MILLION;
    long long F=0;
    long long d = U / N;
    vector<thread> tV;
    vector<long long> f, u, l;
    for (int i = 0; i<N; i++) {
        if (i == 0) {
            l.push_back(2);
            u.push_back(d);
        }
        else {
            l.push_back(u[i - 1] + 1);
            u.push_back(u[i - 1] + d);
        }
    }
    l[N - 1] = U;
    for (int i = 0; i < N; i++) {
        tV.push_back(thread(frequencyOfPrimes, u[i], l[i], &f[i]));
    }

    for_each(tV.begin(), tV.end(), mem_fn(&thread::join));

    ticks = clock() - ticks;

    for (int i = 0; i < N; i++)
        F = f[i] + F;
    cout << "Frequency is " << F << endl;
    cout << "It took " << ticks << " ticks (";
    cout << ((float)ticks) / CLOCKS_PER_SEC << " seconds)" << endl;
    this_thread::sleep_for(chrono::seconds(5));
    return 0;
}

0 个答案:

没有答案