I have been thinking about your first problem for a while and I think I have an algorithm in mind. It has to do with dividing the work between the threads. The thing is, you probably won't see much improvement over a single-threaded version until you get to really big numbers. What ever. You wanted a multi-threaded version so here is one possibility. The first thing to do is what most prime finders do : test the value for divisibility by 2. If it is then it's not a prime number so get that out of the way first because then you eliminate half of the possibilities. Then you always start at 3 and check every odd number after it since the even ones are already ruled out.
Here's where the dividing the work part comes in. Each thread is given a stride value. With one thread the stride is 2. With two threads the stride is 4. This works out to the stride value being twice the number of threads. Correspondingly, the starting point will be :
startingPoint = 3 + ( ( threadIndex - 1 ) * 2 );
This translates to the starting points with four threads will be 3 for thread 1, 5 for thread 2, 7 for thread 3, and 9 for thread 4.
With these values, you could write your test function as :
typedef unsigned long long ULL;
int IsPrime( ULL value, int threadIndex, int threadCount )
{
ULL strideValue = 2 * (ULL) threadCount;
ULL lastValue = value / 2; ULL testValue = 3 + ( ( (ULL) threadIndex - 1 ) * 2 ); while( testValue <= lastValue )
{
if( ( value % testValue ) == 0 )
return 0; testValue += strideValue;
}
return 1; }
The next thing to do is figure out how the threads will report their results. There are a wide variety of ways to do this. One would be to have a single result value and a counter that tells you how many threads have reported. The variables would have their access controlled by a mutex. When a thread finishes it acquires the mutex, sets the result value to true only if its result is true (if false then leave it alone) and then increments the counter. If the thread finds it was the last one (counter == number of threads) it sets a signal indicating the test is done. After all this it releases the mutex.
The next step is to start and signal the threads. This part I will leave to you since it appears that you are using the pthread library and I can't help you with that. I know how threads and signals work in general, but not that library.
There are different ways this algorithm can be used, depending on how you want to test. The IsPrime algorithm was written assuming the threads are testing one value. Another way you can do testing like this is to build a list of prime numbers. For this, you would use a generic IsPrime function written for one thread but you would distribute the values to test as is done in this IsPrime function with different start and stride values, depending on the thread count and index. Then you would need an array of results with a counter controlled by a mutex.