This pthread/C application takes min/max powers (or upper limit),

calculates all primes between 2min and 2max

in two threads and writes found primes to log files.

1. application makes use of libpthread library

pthread_t thread1;
pthread_t thread2;

2. struct prime_parms is used to keep thread specific data - search limits and running time:

struct prime_parms
{
  int start;
  int end;
  struct timeval rtime;
};

3. pthread_key_t is used to associate a log file pointer with each thread

so that threads (sharing process memory) could have their own copy

static pthread_key_t thread_log_key;
4. and use it to write newly found primes to their private log files:
void write_to_thread_log (int prime)
{
  FILE* thread_log = (FILE*) pthread_getspecific (thread_log_key);
  fprintf (thread_log, "%in", prime);
}

5. cleanup function is called when thread exits:

void close_thread_log (void* thread_log)
{
  fclose ((FILE*) thread_log);
}

6. thread_log_key and cleanup function are used to create thread specific data

in main and then store file pointer inside thread function:

pthread_key_create (&thread_log_key, close_thread_log);
...
pthread_setspecific (thread_log_key, thread_log);

7. common thread function and two copies of struct with parameters

are used to create/start threads:

pthread_create (&thread1, NULL, &compute_primes, &parms1);
pthread_create (&thread2, NULL, &compute_primes, &parms2);

8. main thead then waits for search threads to complete and return

number of primes found via nbr:

pthread_join (thread1, (void*) &nbr);
pthread_join (thread2, (void*) &nbr2);

9. application also reports running time of each thread and total

running time in microseconds:

geo@fermat:/home/work$ ./geoprimes 10 20

*** Main Thread ID = -1210722640, pid = 3396 ***

Search limits: min = 2^10 = 1024, half = 524800, max = 2^20 = 1048576

threadID = -1210725488; pid = 3396; log file = primes-1024-524800.log
threadID = -1219118192; pid = 3396; log file = primes-524800-1048576.log


thread1: 43247 primes between 1024 and 524800, runtime=664176(usec)
thread2: 38606 primes between 524800 and 1048576, runtime=297685(usec)

Total number of primes between 2^10 (1024) and 2^20 (1048576) is 81853, runtime=299342(usec).

geo@fermat:/home/work$l *.log
-rw-r--r-- 1 geo geo 292252 2010-08-01 23:04 primes-1024-524800.log
-rw-r--r-- 1 geo geo 273769 2010-08-01 23:04 primes-524800-1048576.log
geo@fermat:/home/work$ tail primes-524800-1048576.log 
1048391
1048423
1048433
1048447
1048507
1048517
1048549
1048559
1048571
1048573
geo@fermat:/home/work$

As you can see it takes less then 0.3 seconds to find all primes between

210 and 220 and write them into two log files.

Not bad result given simplest form of seave used, though it may not be fast enough

to search for record size primes in such manner :-)

You can download app build on Debian Lenny, GCCv4.3.2 from here.