Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <stdio.h>
- #include <math.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <iostream>
- #include <sys/time.h> //measure the execution time of the computations
- using namespace std;
- //The number of thread to be generated
- #define NUMBER_OF_THREADS 4
- void * Prime(void* index);
- long numbers[4] = {2500000, 5000000, 7500000, 10000000};
- long start_numbers[4] = {2, 2500001, 5000001, 7500001};
- int thread_numbers[4] = {0, 1, 2, 3};
- int main(){
- pthread_t tid[NUMBER_OF_THREADS];
- int tn;
- long sum = 0;
- timeval start_time, end_time;
- double start_time_microseconds, end_time_microseconds;
- gettimeofday(&start_time, NULL);
- start_time_microseconds = start_time.tv_sec * 10000000 + start_time.tv_usec;
- for(tn = 0; tn < NUMBER_OF_THREADS; tn++){
- if (pthread_create(&tid[tn], NULL, Prime, (void *) &thread_numbers[tn]) == -1 ) {
- perror("thread fail");
- exit(-1);
- }
- }
- long value[4];
- for(int i = 0; i < NUMBER_OF_THREADS; i++){
- if(pthread_join(tid[i],(void **) &value[i]) == 0){
- sum = sum + value[i]; //add four sums together
- }else{
- perror("Thread join failed");
- exit(-1);
- }
- }
- //get the end time in microseconds
- gettimeofday(&end_time, NULL);
- end_time_microseconds = end_time.tv_sec * 10000000 + end_time.tv_usec;
- //calculate the time passed
- double time_passed = end_time_microseconds - start_time_microseconds;
- cout << "Sum is: " << sum << endl;
- cout << "Running time is: " << time_passed << " microseconds" << endl;
- exit(0);
- }
- //Prime function
- void* Prime(void* index){
- int temp_index;
- temp_index = *((int*)index);
- long sum_t = 0;
- for(long i = start_numbers[temp_index]; i <= numbers[temp_index]; i++){
- for (int j=2; j*j <= i; j++)
- {
- if (i % j == 0)
- {
- break;
- }
- else if (j+1 > sqrt(i)) {
- sum_t++;
- }
- }
- }
- cout << "Thread " << temp_index << " terminates" << endl;
- pthread_exit( (void*) sum_t);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement