Thread Usage in c ++

1

I created a code to check the prime numbers, but I'm trying to use all the cores in my processor to calculate them.

#include <iostream>
#include <Windows.h>
#include <vector>
#include <algorithm>
#include <thread>

using namespace std;
vector<long long> primos;
long long pmax = 50000;

//int i;

bool isprime(__int64 num) {

    int i = sqrt(num);
    int ii = 3;


    if (num == 2) { return true; }
    else if (num % 2 == 0) { return false; }
    else if (i % 2 == 0) { i--; }


    while (ii <= i) {
        if (num%ii == 0) {
            return false;
        }
        ii += 2;
    }
    return true;

}
void prim(int ad, int thr) {
    for (int i = (3 + ad); i < pmax; i += (thr * 2)) {
        if (isprime(i)) {
            primos.push_back(i);
        }
    }

}

int tr = 2;
void p1() {
    prim(0, tr);
}

void p2() {
    prim(2, tr);
}
void p3() {
    prim(4, tr);
}
void p4() {
    prim(6, tr);
}
void p5() {
    prim(8, tr);
}
void p6() {
    prim(10, tr);
}
void p7() {
    prim(12, tr);
}
void p8() {
    prim(14, tr);
}

int main() {
    int t = GetTickCount();
    int d1, d2;
    primos.push_back(2);

    thread t1{ p1 } , t2{ p2 };//, t3{ p3 }, t4{ p4 };// , t5{ p5 }, t6{ p6 };//, t7{ p7 }, t8{ p8 };


    t1.join();
    t2.join();
    //t3.join();
    //t4.join();
    //t5.join();
    //t6.join();
    //t7.join();
    //t8.join();

    d1 = GetTickCount() - t; t = GetTickCount();
    sort(primos.begin(), primos.end());
    d2 = GetTickCount() - t;

    cout << "Tempo para calcular: " << d1 << " ms\nTempo para ordenar: " << d2 << " ms\n\n";

    system("pause");
}

Whenever I put more than one thread it returns some errors. Sometimes the thread says it triggered a breakpoint and the times the heap was corrupted.

I'm still new to c ++. If you can help me understand what happened, I'm grateful.

    
asked by anonymous 03.03.2017 / 22:51

1 answer

0

You need to protect the cousin vector with a mutex , so only one thread at a time can change that vector. Usually data structures can not be changed by more than one thread at a time, this usually causes memory corruption or other bad things.

// ....
// ....
#include <mutex>
// ....
// ....
using namespace std;
vector<long long> primos;
// ...
mutex globalMutex;
// ...
// ...
void prim(int ad, int thr)
{
   for (int i = (3 + ad); i < pmax; i += (thr * 2))
   {
      if (isprime(i))
      {
         lock_guard<mutex> guard(globalMutex);  // <------------
         primos.push_back(i);
      }
   }
}
// ...
// ...
    
03.03.2017 / 23:52