> for (int i = 5; i <= sqrt(num); i = i + 6)
Precalculate the square root, you're doing this every time around the loop.
> for (int i = 0; i < run_n / NUM_THREADS; ++i)
Not sure why you're not using your var parameter here.
> int random = rand();
1. Beware of the possibly limited range of rand(). What is RAND_MAX on your system?
2. Use rand_r() in a multi-threaded program.
rand(3): pseudo-random number generator - Linux man page
> if (count == run_n)
> return 0;
Yeah, you return with the mutex still locked. This isn't good.
It doesn't actually seem to serve any purpose though, as only the last thread on the last iteration would hit this condition, and the loop is going to end anyway.
> sum += random;
> primeCounter++;
You print both of these, but neither are protected by the mutex.
> #define run_n 1000000
Possibly too small for you to notice a difference.
Creating threads isn't free, and your mutex on every iteration in every thread is going to sap performance.
Code:
void *func(void *var)
{
long local_sum = 0, local_counter = 0;
unsigned int seed = 1; //!! use your var in some way
for (int i = 0; i < run_n / NUM_THREADS; ++i)
{
int random = rand_r(&seed);
if (isPrime(random))
{
local_sum += random;
local_counter++;
}
}
pthread_mutex_lock(&lock);
sum += local_sum;
primeCounter += local_counter;
pthread_mutex_unlock(&lock);
return NULL;
}