1 /*
2 Copyright 2006 Paul... don't copy this for your hw...^M
3 Author: Paul Picazo (http://pr.erau.edu/~picazdb3/)^M
4 Course: CS420 Operating Systems^M
5 Instructor : Matt Jaffe
6 Prime calculator code adapted from http://www.tekpool.com/
7 Compile with g++ instead of gcc, sqrt gives linker error in gcc
8 otherwise without the sqrt it should compile as c in gcc
9 Be sure to link the phthread (-lpthread option in g++) library.
10 Example:
11 g++ thread.cpp -lpthread -o thread
12 */
13 #include <stdio.h>
14 #include <pthread.h>
15 #include <math.h>
16 #include <sys/select.h>
17
18 //largest number (+1) that will be checked to see if its a prime
19 #define MAXX 10000000
20
21 //thread description records
22 pthread_t display;
23 pthread_t calc;
24
25 //thread attribute records
26 pthread_attr_t display_attr;
27 pthread_attr_t calc_attr;
28
29 //current number to check if prime
30 int j;
31
32 //number of primes found
33 int count;
34
35 //Function adpated from http://www.tekpool.com/?p=18
36 void* calcPrimes(void* args)
37 {
38 int i;
39 j=3;
40 count = 1;
41 while(j < MAXX)
42 {
43 int check = (int)sqrt((double)(j));
44 int fPrimeFound=1;
45 for(i=2; i<=check; i++)
46 {
47 if(j%i==0)
48 {
49 fPrimeFound=0;
50 break;
51 }
52 }
53 if(fPrimeFound)
54 {
55 count++;
56 }
57 j++;
58 }
59 }
60
61 void* displayInfo(void* args)
62 {
63 int alive = 1;
64 int percent = 0;
65 timeval tv;
66 tv.tv_sec = 0;
67 tv.tv_usec = 0;
68 while(alive)
69 {
70 percent = (int)((double)j / (double)MAXX * 100);
71 printf("\n%d%\tLast Number Checked:%d\tPrimes Found:%d",
72 percent,j,count);
73 if(percent == 100)
74 {
75 printf("\n");
76 alive = 0;
77 }
78 else
79 {
80 //wait for 10000 microseconds before looping again
81 select(0, NULL, NULL, NULL, &tv);
82 tv.tv_usec = 10000;
83 }
84 }
85 }
86
87 int main()
88 {
89 //set the default thread attributes
90 pthread_attr_init(&display_attr);
91 pthread_attr_init(&calc_attr);
92
93 //set the threads to kernel level
94 pthread_attr_setscope(&display_attr, PTHREAD_SCOPE_SYSTEM);
95 pthread_attr_setscope(&calc_attr, PTHREAD_SCOPE_SYSTEM);
96
97 //create the threads
98 pthread_create(&display, NULL, displayInfo, (void*)"hello");
99 pthread_create(&calc, NULL, calcPrimes, (void*)"hi");
100
101 //wait for threads to terminate
102 pthread_join(display, NULL);
103 pthread_join(calc, NULL);
104
105 return 0;
106 }