-
Notifications
You must be signed in to change notification settings - Fork 0
/
Oving1.cpp
63 lines (51 loc) · 1.19 KB
/
Oving1.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
using namespace std;
vector<int> primes;
mutex prime_mutex;
bool check_if_prime(int num){
if (num == 0 || num == 1){
return false;
}
else {
for (int i = 2; i <= num / 2; ++i){
if (num % i == 0){
return false;
}
}
}
return true;
}
void FindPrimes(int start, int end){
while(start < end){
if (check_if_prime(start)){
prime_mutex.lock();
primes.push_back(start);
prime_mutex.unlock();
}
++start;
}
}
void UseThreads(int start, int end, int numOfThreads){
vector<thread> threads;
int numPerThread = (end - start) / numOfThreads;
int localEnd = start + numPerThread;
for (int i = 0; i < numOfThreads; i++){
threads.emplace_back(FindPrimes, start, localEnd);
start += numPerThread;
localEnd += numPerThread;
}
for (auto& t : threads){
t.join();
}
}
int main()
{
UseThreads(0, 100, 3);
for (auto i: primes){
cout << i << " ";
}
return 0;
}