Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <iostream>
- #include <ctime>
- #include <cmath>
- #pragma comment(lib, "pthreadVCE2.lib")
- struct parameters_t {
- int start;
- int end;
- int number;
- bool result;
- };
- bool naive() {
- const int number = 499999219;
- int currentDelimiter = 2;
- while (currentDelimiter * currentDelimiter < number) {
- if (number % currentDelimiter == 0)
- return false;
- currentDelimiter++;
- }
- return true;
- }
- auto t = true;
- auto f = false;
- void* routine(void* parameters) {
- auto p = (parameters_t*)parameters;
- for (auto i = p->start; i < p->end; i++) {
- if (p->number % i == 0) {
- return (void*)false;
- }
- }
- return (void*)true;
- }
- void testParallel() {
- const int threadCount = 4;
- const int number = 499999219;
- auto intervalWidth = (number - 2) / threadCount;
- pthread_t* threads = new pthread_t[threadCount];
- auto params = new parameters_t[threadCount];
- auto results = new bool[threadCount];
- for (auto i = 0; i < threadCount; i++) {
- params[i] = parameters_t();
- params[i].start = i == 0 ? 2 : i * intervalWidth;
- params[i].end = i == threadCount - 1 ?
- number - 1 : params[i].start + intervalWidth - 1;
- params[i].number = number;
- pthread_create(&threads[i], nullptr, routine, ¶ms[i]);
- }
- for (auto i = 0; i < threadCount; i++) {
- void* localResult;
- pthread_join(threads[i], &localResult);
- results[i] = (bool)localResult;
- printf("Thread#%d returned %d\n", i, results[i]);
- }
- auto result = false;
- for (int i = 0; i < threadCount; i++) {
- result = results || results[i];
- }
- printf(result ? "Not Prime" : "Prime");
- printf("\n");
- }
- int main() {
- auto start = clock();
- for (auto i = 0; i < 1; i++) {
- testParallel();
- // naive();
- }
- auto end = clock();
- auto ms = end - start;
- printf("Ellapsed: %ld ms", ms);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement