#include #include #include using std::cout; using std::cerr; using std::cin; using std::endl; // Must compile with -pthread struct Data { unsigned int num; pthread_mutex_t mut; }; void * RunThread(void *ptr); int main() { unsigned int posInt = 1; Data d; void *pRtnValue; pthread_t myThread; d.num = 1; pthread_mutex_init(&d.mut, NULL); pthread_create(&myThread, NULL, RunThread, &d); while(posInt) { cout << "Enter a positive integer:"; cin >> posInt; pthread_mutex_lock(&d.mut); d.num = posInt; pthread_mutex_unlock(&d.mut); pthread_yield(); } /* Wait for the thread to quit */ if(pthread_join(myThread, &pRtnValue) == 0) { cerr << "Thread terminated" << endl; } else { cerr << "Error on thread termination" << endl; } return 0; } void * RunThread(void *ptr) { Data *dataPtr = (Data*)ptr; bool stillGoing = true; while(stillGoing) { sleep(1); pthread_mutex_lock(&dataPtr->mut); if(dataPtr->num == 0) { stillGoing = false; } else { dataPtr->num++; cout << " " << dataPtr->num << endl; } pthread_mutex_unlock(&dataPtr->mut); pthread_yield(); } pthread_exit(ptr); }