Hi,

Currently I am playing with multithreading a bit. I use POSIX threads (header file: pthread.h). I quickly read some tutorials and I wanted to apply what I had learned to a prime calculation program. The user inputs number of threads and maximum number to calculate. This works perfectly, no compiler errors or warnings and no segmentation faults. The prime numbers are correct and in the right order (I roughly checked up to 100).

However, when I am benchmarking I get longer times when using more threads.

I think this is the problem area:

Code:
for (i = 3; i < primes; i += threads+1) // +1 compensates for isPrime calculation in parent
    {
        for (j = 0; j < threads; ++j)
        {
            temp[j] = i + j;
            pthread_create(&tid[j], NULL, (void *)isPrime, &temp[j]);
        }

        *tempParent = i + threads;
        isPrime((unsigned int *)tempParent);

        for (j = 0; j < threads; ++j)
        {
            ret[j] = pthread_join(tid[j], NULL);

            if(temp[j] != 0)
            {
                printf ("%d\n", temp[j]);
            }
        }

        if(*tempParent != 0)
        {
            printf ("%d\n", *tempParent);
        }
    }
temp, parentTemp, ret, tid are allocated using malloc(). The isPrime(unsigned int *n) function sets the value of the pointer passed to it to zero if *n isn't a prime number.

I want the threads and the parent to isPrime() at the same time, but that doesn't happen, because there is no speed gain?

I calculated up to 1,000,000, roughly benchmarking with time_t and time() in seconds. With 1 thread compared to 5 threads, 5 threads is seconds slower!

Thanks