// File: TwoThreads.cpp // Written by Dr. Spiegel // Last Revision: 11/16/2014 // Simple example to show thread interaction // Each thread's loop iterates argv[1] times #include #include #include // for perror #include using namespace std; void *task1(void *X); void *task2(void *X); int main(int argc, char *argv[]) { pthread_t ThreadA,ThreadB; int N; if(argc != 2){ cout << "error" << endl; exit (1); } N = atoi(argv[1]); int res; if ((res=pthread_create(&ThreadA,NULL,task1,&N))<0) { perror("pThread creation"); cerr << "Thread creation returned " << res << endl; exit(-1); } pthread_create(&ThreadB,NULL,task2,&N); cout << "waiting for threads to join" << endl; pthread_join(ThreadA,NULL); pthread_join(ThreadB,NULL); return(0); } void *task1(void *X) { int *Temp; Temp = static_cast(X); cout << "task1: Temp is " << *Temp << endl; for(int Count = 1;Count < *Temp;Count++){ cout << "work from thread A: " << Count << " * 2 = " << Count * 2 << endl; } cout << "Thread A complete" << endl; } void *task2(void *X) { int *Temp; Temp = static_cast(X); cout << "task2: Temp is " << *Temp << endl; for(int Count = 1;Count < *Temp;Count++){ cout << "work from thread B: " << Count << " + 2 = " << Count + 2 << endl; } cout << "Thread B complete" << endl; }