86 lines
1.8 KiB
C
86 lines
1.8 KiB
C
#include <stdio.h>
|
|
#include <pthread.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <unistd.h>
|
|
|
|
bool is_prime(const int n) {
|
|
for (int i = 2; i < n; i++) {
|
|
if (n % i == 0) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
void* aThread(void *ptr) {
|
|
const int *arr = (int *)ptr;
|
|
//printf("%d, %d\n", arr[0], arr[1]);
|
|
const int r = arr[1]-arr[0];
|
|
int *n = malloc(r * sizeof(int));
|
|
if (n == nullptr) perror("fail");
|
|
memset(n, 0, r);
|
|
int c = 0;
|
|
|
|
for (int i = arr[0]; i < arr[1]; i++) {
|
|
if (is_prime(i)) {
|
|
n[c] = i;
|
|
c++;
|
|
}
|
|
}
|
|
|
|
n[c+1] = -1;
|
|
|
|
return n;
|
|
}
|
|
|
|
int get_threads() {
|
|
const int num_cores = (int)sysconf(_SC_NPROCESSORS_ONLN); // Logical cores online
|
|
if (num_cores == -1) {
|
|
perror("sysconf");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
|
|
return num_cores;
|
|
}
|
|
|
|
int main(void) {
|
|
const int thr_num = get_threads();
|
|
constexpr int max_prime = 2000000;
|
|
const int slice = max_prime / thr_num;
|
|
pthread_t thread_id[thr_num];
|
|
|
|
int start = 2;
|
|
|
|
for (int i = 0; i < thr_num; i++) {
|
|
int *arr = malloc(2 * sizeof(int));
|
|
if (arr == nullptr) perror("Failed!");
|
|
memset(arr, 0, 2);
|
|
arr[0] = start;
|
|
arr[1] = (start + slice) > max_prime ? max_prime : start + slice;
|
|
|
|
pthread_create(&thread_id[i], nullptr, aThread, arr);
|
|
start = arr[1];
|
|
}
|
|
|
|
int c = 0;
|
|
|
|
for (int i = 0; i < thr_num; i++) {
|
|
void *thread_res = nullptr;
|
|
pthread_join(thread_id[i], &thread_res);
|
|
int *result = (int *)thread_res;
|
|
int prime = 0;
|
|
|
|
for (int t = 0;; t++) {
|
|
prime = result[t];
|
|
if (prime == -1 || prime == 0) break;
|
|
printf("%d\n", prime);
|
|
c++;
|
|
}
|
|
}
|
|
|
|
printf("Together %d.", c);
|
|
|
|
exit(EXIT_SUCCESS);
|
|
} |