Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdio>
- #include <vector>
- #include <iostream>
- #include <algorithm>
- #include <pthread.h>
- #include <cmath>
- #include<stdio.h>
- // Zrobić 2 zadania z Lab 7 w instrukcji.
- std::vector<int> * primes = NULL;
- pthread_mutex_t * mutex = NULL;
- typedef struct job {
- int num;
- } job;
- void cache_prime(int prime) {
- pthread_mutex_lock(mutex);
- primes->push_back(prime);
- pthread_mutex_unlock(mutex);
- }
- void * worker(void * params) {
- int target = ((job *)params)->num;
- printf("Calculating: %d \n", target);
- //std::cout << "Calculating: " << target << std::endl;
- for (int i = 2; i < target; i++) {
- if (target % i == 0) {
- printf("%d is not prime.\n", target);
- //std::cout << target << " is not prime..." << std::endl;
- return NULL;
- }
- }
- printf("%d is prime! \n", ((job *)params)->num);
- //std::cout << ((job *)params)->num << " is prime!" << std::endl;
- cache_prime(((job *)params)->num);
- return NULL;
- }
- int main() {
- int from = 4, to = 100;
- mutex = new pthread_mutex_t;
- primes = new std::vector<int>();
- pthread_mutex_init(mutex, NULL);
- pthread_t * threads[4] = { NULL };
- job * jobs[4] = { NULL };
- if (from > to) std::swap(from, to);
- if (from <= 1) from = 2;
- if (to <= 1) to = 2;
- printf("Looking for primes between %d and %d (inclusive)...\n", from, to);
- //std::cout << "Looking for primes between " << from << " and " << to << " (inclusive)..." << std::endl;
- for (int i = from; i <= to; i++) {
- int thread_index = (i - from) % 4;
- if (threads[thread_index] != NULL) {
- pthread_join((*threads[thread_index]), NULL);
- delete threads[thread_index];
- free(jobs[thread_index]);
- threads[thread_index] = NULL;
- }
- job * work = (job *)malloc(sizeof(work));
- work->num = i;
- threads[thread_index] = new pthread_t;
- pthread_create(threads[thread_index], NULL, worker, work);
- jobs[thread_index] = work;
- }
- for (int i = 0; i < 4; i++) {
- if (threads[i] != NULL) pthread_join((*threads[i]), NULL);
- }
- for (int i = 0; i < primes->size(); i++)
- printf("%d, ", primes->data()[i]);
- printf("done.\n")
- //std::cout << "done." << std::endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement