/* Programming with pthread: pthread1.c++ one thread computes factorial and the other thread computes fibonacci $ g++ -Wall pthread1.c++ -lpthread $ ./a.out 5 */ #include using namespace std; #include #include #include #include #define loop(X) {for(int i=0; i<=(X); ++i);} void * thread1(void *) ; void * thread2(void *) ; int eS1, eS2; int fact(int n){ if(n == 0) return 1 ; return n*fact(n-1) ; } int fib(int n) { int f0 = 0, f1 = 1, i ; if(n == 0) return f0 ; if(n == 1) return f1 ; for(i=2; i<=n; ++i) { int temp = f0 ; f0 = f1 ; f1 = f0 + temp ; } return f1 ; } int main(int count, char *vect[]) { pthread_t thID1, thID2; // thread ID int n ; // pthread1.c++ int err, *esP1, *esP2; if(count < 2) { cerr << "No argument for function\n" ; exit(1) ; } n = atoi(vect[1]) ; cout << "main thread: n = " << n << "\n" ; err = pthread_create(&thID1, NULL, thread1, (void *) &n); // 1st child thread1 if(err != 0){ cerr << "Thread 1 creation problem\n"; exit(1); } err = pthread_create(&thID2, NULL, thread2, (void *) &n); // 2nd child thread2 if(err != 0){ cerr << "Thread 2 creation problem\n"; exit(1); } pthread_join(thID2, (void **)&esP2);// 2nd thread joins pthread_join(thID1, (void **)&esP1);// 1st thread joins cout << "Thread 1: " << *esP1 << endl; cout << "Thread 2: " << *esP2 << endl; return 0 ; } void *thread1(void *vp) {// Address of parameter int i, *p ; // to pass p = (int *) vp ; for(i=0; i<=*p; ++i) { cout << "Th1: fib(" << i << ") = " << fib(i) << endl ; loop(5000000); } eS1 = 1; pthread_exit((void *)&eS1) ; } void *thread2(void *vp) {// Address of parameter int i, *p; // to pass p = (int *) vp ; for(i=0; i<=*p; ++i) { cout << "Th2:" << i << "! = " << fact(i) << endl ; loop(5000000); } eS2 = 2; pthread_exit((void *)&eS2) ; }