/* Copyright 2006 Paul... don't copy this for your hw... Author: Paul Picazo (http://pr.erau.edu/~picazdb3/) Course: CS420 Operating Systems Instructor : Matt Jaffe Prime calculator code adapted from http://www.tekpool.com/ Compile with g++ instead of gcc, sqrt gives linker error in gcc otherwise without the sqrt it should compile as c in gcc Be sure to link the phthread (-lpthread option in g++) library. Example: g++ thread.cpp -lpthread -o thread */ #include #include #include #include //largest number (+1) that will be checked to see if its a prime #define MAXX 10000000 //thread description records pthread_t display; pthread_t calc; //thread attribute records pthread_attr_t display_attr; pthread_attr_t calc_attr; //current number to check if prime int j; //number of primes found int count; //Function adpated from http://www.tekpool.com/?p=18 void* calcPrimes(void* args) { int i; j=3; count = 1; while(j < MAXX) { int check = (int)sqrt((double)(j)); int fPrimeFound=1; for(i=2; i<=check; i++) { if(j%i==0) { fPrimeFound=0; break; } } if(fPrimeFound) { count++; } j++; } } void* displayInfo(void* args) { int alive = 1; int percent = 0; timeval tv; tv.tv_sec = 0; tv.tv_usec = 0; while(alive) { percent = (int)((double)j / (double)MAXX * 100); printf("\n%d%\tLast Number Checked:%d\tPrimes Found:%d", percent,j,count); if(percent == 100) { printf("\n"); alive = 0; } else { //wait for 10000 microseconds before looping again select(0, NULL, NULL, NULL, &tv); tv.tv_usec = 10000; } } } int main() { //set the default thread attributes pthread_attr_init(&display_attr); pthread_attr_init(&calc_attr); //set the threads to kernel level pthread_attr_setscope(&display_attr, PTHREAD_SCOPE_SYSTEM); pthread_attr_setscope(&calc_attr, PTHREAD_SCOPE_SYSTEM); //create the threads pthread_create(&display, NULL, displayInfo, (void*)"hello"); pthread_create(&calc, NULL, calcPrimes, (void*)"hi"); //wait for threads to terminate pthread_join(display, NULL); pthread_join(calc, NULL); return 0; }