Here is the program I created!
Code: Select all
#include <stdio.h>
#include <pthread.h>
typedef struct
{
int start;
int end;
int step;
}data;
int isPrime(long int number)
{
long int i;
for(i=2; i<number; i++)
{
if(number % i == 0)
{
//not a prime
return 0;
}
}
return number;
}
void calcPrimes(int start, int stop, int step)
{
long int s;
for(s=start; s<=stop; s+=step)
{
if (isPrime(s) > 0)
{
//Its a prime number!!!
}
}
}
void* thread1Go()
{
calcPrimes(3, 100000, 8); //stepping 8 numbers for 4 cores
return NULL;
}
void* thread2Go()
{
calcPrimes(5, 100000, 8); //starting thread 2 at the next odd number jumping 8 spaces for 4 cores
return NULL;
}
void* thread3Go()
{
calcPrimes(7, 100000, 8); // starting thread 2 at the next odd number and jumping 8 spaces for a 4 core run
return NULL;
}
void* thread4Go()
{
calcPrimes(9, 100000, 8); // think you get it.
return NULL;
}
int main()
{
printf("Calculate Prime Numbers\n");
printf("==================================================\n\n");
//create the threads
pthread_t thread0;
pthread_create(&thread0, NULL, thread1Go, NULL);
pthread_t thread1;
pthread_create(&thread1, NULL, thread2Go, NULL);
pthread_t thread2;
pthread_create(&thread2, NULL, thread3Go, NULL);
pthread_t thread3;
pthread_create(&thread3, NULL, thread4Go, NULL);
//wait for threads to join before exiting
pthread_join(thread0, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_join(thread3, NULL);
return 0;
}
And my results were not quite what I was expecting... sort of!
1 thread = 33.016 s
2 thread = 16.531 s
3 thread = 16.637 s <= WTF!!!
4 thread = 8.871 s
I noticed that running on 3 threads the activity seemed only to be divided by 2 cores.... thought I would see 3 active cores and one ticking over?
But its great to see a massive performance increase by having the extra cores to play with.
I thought this was interesting so I shared it.