Use of Thread in c++

Asked

Viewed 388 times

1

I created a code to check the prime numbers, but I’m trying to use the core of 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 speaking the thread triggered a breakpoint and the times the heap was corrupted.

I’m still a novice at c++. If you can help me understand what happened, I’m grateful.

1 answer

0


You need protect the vector of primes with a mutex, so that only one thread at a time can change this vector. Usually data structures cannot be changed by more than one thread at the same 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);
      }
   }
}
// ...
// ...
  • It gave right It just increased the time to process, but has improved enough Vlw ^^

  • then mark the answer as accepted, please...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.